Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access childnodes' children in javascript

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;
like image 556
Athapali Avatar asked Sep 07 '26 03:09

Athapali


1 Answers

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.

like image 105
lonesomeday Avatar answered Sep 11 '26 17:09

lonesomeday