how to count total number of divs inside another div using javascript

前端 未结 2 1854
粉色の甜心
粉色の甜心 2021-02-19 20:07

How to count the total number of div elements that are contained in another div using javascript?

相关标签:
2条回答
  • 2021-02-19 20:48

    The getElementsByTagName() is not only a document method, but one that can run on any DOM element.

    element.getElementsByTagName is similar to document.getElementsByTagName, except that its search is restricted to those elements which are descendants of the specified element

    see more at https://developer.mozilla.org/en/DOM/element.getElementsByTagName


    So the actual code that does what you ask is

    var container_div = document.getElementById('id_of_container_div');
    var count = container_div.getElementsByTagName('div').length;
    
    0 讨论(0)
  • 2021-02-19 20:48

    You can use @davidcmoulton's handy Gist: https://gist.github.com/davidcmoulton/a76949a5f35375cfbc24

    I find it quite useful that it doesn't only count DIVs but also lists the count of all element types of your page.

    Here is a copy of the Gist for further reference:

    (function (window, undefined) {
    //  Counts all DOM elements by name & logs resulting object to console. 
    var forEach = Array.prototype.forEach,
    counter = {},
    
    incrementElementCount = function (elementName) {
      if (counter.hasOwnProperty(elementName)) {
        counter[elementName] += 1;
      } else {
        counter[elementName] = 1;
      }
    },
    
    processNode = function (node) {
      var currentNode = node;
      if (currentNode.nodeType === currentNode.ELEMENT_NODE) {
        incrementElementCount(currentNode.nodeName);
        if (currentNode.hasChildNodes) {
          forEach.call(currentNode.childNodes, function (childNode) {
            if (childNode.nodeType === currentNode.ELEMENT_NODE) {
              processNode(childNode);
            }
          });
        }
      }
    };
    
    processNode(window.document.firstElementChild);
    
    console.log(counter);
    
    }(this));
    
    0 讨论(0)
提交回复
热议问题