3

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.

3 Answers 3

17

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

and done.


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

would also work.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks for the prompt answer.
2

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

Comments

1

jQuery recursive child node count function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.