how to count total number of divs inside 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));

Tags:

Javascript