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

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

提交回复
热议问题