Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get child elements by className

Tags:

javascript

I have written the following line in Javascript:

var eleCategory = document.getElementById("cmbCategory");

Now I want to find all elementbyClassName contained in the eleCategory element.

Is it possible with something like this?

 var eleChild = eleCategory.getElementByClassName("autoDropdown");

How can I get the child element of the parent element?

like image 550
ghanshyam.mirani Avatar asked Dec 01 '11 07:12

ghanshyam.mirani


3 Answers

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>
like image 199
Niels Avatar answered Oct 07 '22 08:10

Niels


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

like image 25
canon Avatar answered Oct 07 '22 06:10

canon


var eleChild = eleCategory.childNodes;
for( i = 0 , j = eleChild.length; i < j ; i++ ){
    if( eleChild[ i ].className == "autodropdown" ){
        YOUr_SCRIPT
    }
}
like image 41
Michael Sazonov Avatar answered Oct 07 '22 07:10

Michael Sazonov