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

前端 未结 3 807
南旧
南旧 2021-02-04 23:14

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         


        
相关标签:
3条回答
  • 2021-02-04 23:56

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

    myDiv.querySelectorAll("*")
    
    0 讨论(0)
  • 2021-02-04 23:58

    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);
         }
      }
    }
    
    0 讨论(0)
  • 2021-02-05 00:04

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

    myDiv.getElementsByTagName("*")
    
    0 讨论(0)
提交回复
热议问题