javascriptarraysnodevalue

recursively log all children of all children in dom


I'm trying to get all the children recursively in the DOM. I've looked at some other examples but they were a little too excessive for what I'm trying to do. Basically I just want to grab all the nodeValues of the nodes on a page assuming they look something like the following.

child
   child
       child
-------------------
child
    child
-------------------
child
-------------------
child
   child
      child
-------------------

my current code is as follows but it only scoops down one layer and assumes that a child would not have another X children. I don't want to keep making for loops so I was hoping someone could introduce me to a good recursive method instead?

   //check all children inside a child
          for(let j = 0; j < children[i].length; j++){
              console.log(children[i][j])
                      }
                  } 

Solution

  • document.querySelectorAll('body *') should return every DOM element in the body and flatten them out if that is what you need.

    If you are looking for a recursive function

    var elements = [];
    var recursiveFindChildren = function(el) {
      for (let i = 0, iLength = el.children.length; i<iLength; i++) {
        elements.push(el.children[i]);
        if (el.children[i].children.length) recursiveFindChildren(el.children[i]);
      }
      return elements;
    }
    
    recursiveFindChildren(document.body)