How do i access child nodes of a child node in javascript? I need to target the img inside of each li and get its width and height. I want to do this without using jquery. Just pure javascript.
<ul id="imagesUL">
<li>
<h3>title</h3>
<img src="someURL" />
</li>
</ul>
var lis = document.getElementById("imagesUL").childNodes;
The ideal way to do this is with the querySelectorAll function, if you can guarantee that it will be available (if you are designing a site for mobile browsers, for instance).
var imgs = document.querySelectorAll('#imagesUL li img');
If you can't guarantee that, however, you'll have to do the loop yourself:
var = lis = document.getElementById("imagesUL").childNodes,
imgs = [],
i, j;
for (i = 0; i < lis.length; i++) {
for (j = 0; j < lis[i].childNodes.length; j++) {
if (lis[i].childNodes[j].nodeName.toLowerCase() === 'img') {
imgs.push(lis[i].childNodes[j]);
}
}
}
The above snippet of code is an excellent argument for using a library like jQuery to preserve your sanity.
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