开发者

Is there a JS/jQuery Fully Recursive child node count function?

开发者 https://www.devze.com 2023-02-11 17:52 出处:网络
Folks, Let\'s say that I have the following situation: <div class=\"outer\"> <div> <span>

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/jQue开发者_StackOverflow中文版ry or should I write a function just for this issue? TIA.


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

精彩评论

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