Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all childNodes in JS including all the 'grandchildren'?

Tags:

javascript

I want to scan a div for all childNodes including the ones that are nestled within other elements. Right now I have this:

var t = document.getElementById('DivId').childNodes; for(i=0; i<t.length; i++) alert(t[i].id); 

But it only gets the children of the Div and not the grandchildren. Thanks!

Edit: This question was too vague. Sorry about that. Here's a fiddle:

http://jsfiddle.net/F6L2B/

The body.onload script doesn't run at JSFiddle, but it works, except that the 'Me Second' and 'Me Third' input fields are not being assigned a tabIndex and are therefore being skipped over.

like image 725
Michael Swarts Avatar asked Nov 30 '11 06:11

Michael Swarts


People also ask

How do you get a list of childNodes?

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object. By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.

What is the difference between childNodes and children in Javascript?

The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes.

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.


1 Answers

This is the fastest and simplest way, and it works on all browsers:

myDiv.getElementsByTagName("*") 
like image 149
rvighne Avatar answered Sep 23 '22 23:09

rvighne