How to get the number of DOM elements used in a web page

后端 未结 4 509
清歌不尽
清歌不尽 2021-01-30 02:56

Using jQuery I can get easily the number of DOM elemetns used by a web page:

$(\'*\').length;

But not all web sites are using jQuery.

相关标签:
4条回答
  • 2021-01-30 03:32

    The main answer doesn't really count everything (I think shadow DOM would be excluded)

    Using snippet below works better for me:

    $$('*').length
    
    0 讨论(0)
  • 2021-01-30 03:38

    Assuming you mean "HTMLElementNodes" as opposed to "All nodes" (which would include such things as text nodes and also be skipped by your jQuery example) then:

    document.getElementsByTagName('*').length
    

    This still requires the use of DOM though. Pure JavaScript can't interact with an HTML document other than as a string of text.

    0 讨论(0)
  • 2021-01-30 03:47

    It's quite simple really:

    document.getElementsByTagName('*').length
    

    If you can ignore older browsers, you could also preserve some of the jQuery-like syntax with:

    var $;
    $ = document.querySelectorAll.bind(document);
    $('*').length;
    
    0 讨论(0)
  • 2021-01-30 03:48

    Using a recursive function countChildrenNumber:

    function countChildrenNumber(el) {
      let result = 0
      if (el.children && el.children.length > 0) {
        result = result + el.children.length
        for (let i = 0; i < el.children.length; i++) {
          result = result + countChildrenNumber(el.children[i])
        }
      }
      return result
    }
    

    then call it by passing document as the parameter

    countChildrenNumber(document)
    
    0 讨论(0)
提交回复
热议问题