开发者

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

开发者 https://www.devze.com 2022-12-20 03:01 出处:网络
How to c开发者_开发技巧ount the total number of div elements that are contained in another div using javascript?The getElementsByTagName() is not only a document method, but one that can run on any DO

How to c开发者_开发技巧ount the total number of div elements that are contained in another div using javascript?


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;


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


There are many way to count divs element using jquery.

But most popular and simple way are:

$(document).ready(function(){ 
  var divCount = $("div").size();
  alert(divCount);
});

AND

$(document).ready(function(){ 
  var divCount = $("div").length;
  alert(divCount);
});

Its helpful for you

0

精彩评论

暂无评论...
验证码 换一张
取 消