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

前端 未结 2 1853
粉色の甜心
粉色の甜心 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

    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));
    

提交回复
热议问题