Targeting class name iterations with JS

2019-08-07 04:23发布

问题:

I am trying to parse JSON data into specific iterations of a class name "slide_content"

To get something like this:

slide_content[0]

But JS doesn't provide a getElementByClass() selector.

The API data in question is here: Converting Straight JS to JQuery

Cheers! Myles

回答1:

Use jQuery. It allows you to use $('.someClass') to retrieve all elements with a given class name.

If you cannot use jQuery or another JS library for some reason, simply use the Sizzle selector engine which is also used by jQuery - it's not very much code so you could even copy&paste it into one of your project's JS files (but don't do that, it's ugly :p). But since you tagged your question with jquery I assume you can use jQuery...



回答2:

Newer browsers (IE9 and above) have support for document.getElementsByClassName (which ironically means that it has less support than querySelectorAll, but I digress...), but that probably won't meet your compatibility needs. In this case, you can use something like this to get an Array of nodes with the class.

var nodes = document.getElementsByTagName('*'),
    targetClass = 'myclass',
    result = [];

for(var i = 0, l = nodes.length; i < l; i++){
    if((nodes[i].className + ' ').indexOf(targetClass + ' ') !== -1){
        result.push(nodes[i]);
    }
}

This is not an exact duplicate of getElementsByClassName, since that function returns a NodeList, but it should be close enough for most purposes.