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

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

myDiv.getElementsByTagName("*")

Solution 2 - Javascript

If you're looking for all HTMLElement on modern browsers you can use:

myDiv.querySelectorAll("*")

Solution 3 - Javascript

What about great-grandchildren?

To go arbitrarily deep, you could use a recursive function.

var alldescendants = [];

var t = document.getElementById('DivId').childNodes;
    for(let i = 0; i < t.length; i++)
        if (t[i].nodeType == 1)
            recurseAndAdd(t[i], alldescendants);

function recurseAndAdd(el, descendants) {
  descendants.push(el.id);
  var children = el.childNodes;
  for(let i=0; i < children.length; i++) {
     if (children[i].nodeType == 1) {
         recurseAndAdd(children[i]);
     }
  }
}

If you really only want grandchildren, then you could take out the recursion (and probably rename the function)

function recurseAndAdd(el, descendants) {
  descendants.push(el.id);
  var children = el.childNodes;
  for(i=0; i < children.length; i++) {
     if (children[i].nodeType == 1) {
         descendants.push(children[i].id);
     }
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael SwartsView Question on Stackoverflow
Solution 1 - JavascriptrvighneView Answer on Stackoverflow
Solution 2 - JavascriptMad EchetView Answer on Stackoverflow
Solution 3 - JavascriptAdam RackisView Answer on Stackoverflow