javascriptyui

How to get child element by class name?


I'm trying to get the child span that has a class = 4. Here is an example element:

<div id="test">
 <span class="one"></span>
 <span class="two"></span>
 <span class="three"></span>
 <span class="four"></span>
</div>

The tools I have available are JS and YUI2. I can do something like this:

doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');

//or

doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');

These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.

I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though.


Solution

  • Use doc.childNodes to iterate through each span, and then filter the one whose className equals 4:

    var doc = document.getElementById("test");
    var notes = null;
    for (var i = 0; i < doc.childNodes.length; i++) {
        if (doc.childNodes[i].className == "4") {
          notes = doc.childNodes[i];
          break;
        }        
    }
    

    ā€‹