JavaScript get child elements by className

Yes it is possible, see this fiddle: http://jsfiddle.net/ajAY2/

But the getElementsByClassName will return a collection of elements, because it will look for all classes within the object. So if you only got 1 class like that within this object, you have to get the 0th object like:

var eleChild = eleCategory.getElementsByClassName("autoDropdown")[0];

Total script:

Script:

var eleCategory = document.getElementById("cmbCategory");
var eleChild = eleCategory.getElementsByClassName("autoDropdown");
alert(eleChild.length);

HTML

<div id="cmbCategory">

    <div class="autoDropdown"></div>
    <div class="autoDropdown"></div>
</div>

<div class="autoDropdown"></div>

getElementsByClassName hasn't been implemented in all browsers. Niels' solution, for instance, doesn't work in IE. However, others have created their own implementation; John Resig has a write-up on his blog

Tags:

Javascript