最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a JSjQuery Fully Recursive child node count function? - Stack Overflow

programmeradmin5浏览0评论

Folks,

Let's say that I have the following situation:

<div class="outer">
    <div>
        <span>
             <ul>
                 <div> </div>
                 <div> </div>
             </ul>
         </span>
     </div>
  </div>

How would I find the total number of elements inside div.outer? Something like $('div.outer').children().size() or length returns 1 (I'm looking, in this case, for 5) is there a shortcut or function to find the total element count using js/jQuery or should I write a function just for this issue? TIA.

Folks,

Let's say that I have the following situation:

<div class="outer">
    <div>
        <span>
             <ul>
                 <div> </div>
                 <div> </div>
             </ul>
         </span>
     </div>
  </div>

How would I find the total number of elements inside div.outer? Something like $('div.outer').children().size() or length returns 1 (I'm looking, in this case, for 5) is there a shortcut or function to find the total element count using js/jQuery or should I write a function just for this issue? TIA.

Share Improve this question asked Feb 18, 2011 at 15:44 rdodevrdodev 3,1923 gold badges28 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 17

var totalDescendants = $('div.outer *').length;

and done.


var totalDescendants = $('div.outer').find('*').length;

would also work.

A simple (and likely faster than jQuery) JavaScript alternative would be

var el = document.getElementById("foo");
var descendantElementCount = el.getElementsByTagName("*").length;

This does assume you've given the element an id. You could use jQuery to get all the elements with class outer, if this is important:

var descendantElementCount = 0;
$('div.outer').each(function() {
    descendantElementCount += this.getElementsByTagName("*").length;
});

jQuery recursive child node count function:

jQuery(document).ready(function(){ var totalChildren=jQuery("*","div.outer").length; });

发布评论

评论列表(0)

  1. 暂无评论