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?
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
var eleChild = eleCategory.childNodes;
for( i = 0 , j = eleChild.length; i < j ; i++ ){
if( eleChild[ i ].className == "autodropdown" ){
YOUr_SCRIPT
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With