3

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; 

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This works for me:

var children = document.getElementById('imagesUL').children; var grandChildren = []; for (var i = 0; i < children.length; i++) { var child = children[i]; for (var c = 0; c < child.children.length; c++) grandChildren.push(child.children[c]); } 

grandChildren contains all childrens' children.

Libraries like jQuery and UnderscoreJS make this easier to write in a more declarative way.

Comments

0

You can provide a second parameter to the $() function to specify a scope in which to search for the images:

var lis = $('#imagesUL').children(); var images = $('img', lis) images.each(function() { var width = $(this).attr('width'); // ... }); 

1 Comment

how would you do something similar with just javascript?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.