ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

JavaScript get child elements by className

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?

Upvotes: 10

Views: 57993

Answers (5)

Reggie Pinkham
Reggie Pinkham

Reputation: 12708

For elegance, use the querySelector and querySelectorAll methods.

var element = document.querySelector('#Element');
var elementChildren = element.querySelectorAll('.Element-child');

elementChildren will contain an array of all children with a class of Element-child within element.

Using bracket notation we could access the nth child in our array, e.g.

var firstElementChild = elementChildren[0]; // zero-based

Upvotes: 2

Katu
Katu

Reputation: 701

You can access everything in DOM tree, with this:

document.childNodes[0].childNodes[0].childNodes[0] ... n[n] ... 

Just look for childnodes of childnodes. And if I remember right, you can:

var element = document.getElementById("myid");
var child = element.childNode[0]

Upvotes: 2

canon
canon

Reputation: 41665

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

Upvotes: 7

Michael Sazonov
Michael Sazonov

Reputation: 1533

var eleChild = eleCategory.childNodes;
for( i = 0 , j = eleChild.length; i < j ; i++ ){
    if( eleChild[ i ].className == "autodropdown" ){
        YOUr_SCRIPT
    }
}

Upvotes: 4

Niels
Niels

Reputation: 49919

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>

Upvotes: 8

Related Questions