Reputation: 23
I'm having problem in jquery all selectors.
I have three elements within my div, but when i use following lines of code to basically give me the total length of my elements within my div tag although my div contains three elements but it is alerting out 0. Why ?
jquery code:
var element_count = $('#mydiv').find('*').length;
alert(element_count);
HTML Code:
<div id="mydiv">
<p>Hi</p>
<span>Hello</span>
<h1>hey</h1>
</div>
Upvotes: 0
Views: 76
Reputation: 11741
Wrap ur code in document.ready to make sure DOM is ready and then try below code.
$(document).ready(function()
{
var element_count = $('#mydiv').children().length;
}
Demo :-
As mentioned in jquery website http://api.jquery.com/children/ :-
The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.
another option is .find as shown in ur code but you are missing document.ready in your case!
Upvotes: 1
Reputation: 13813
You can use the .children()
method to get a list of contained elements. You only get the direct children.
var contents = $("#myDiv").children();
var content_count = contents.length;
Upvotes: 0
Reputation: 82251
The reason that this code is not working is either its not executed or the DOM is not ready when the code is executed. Make sure you have wrapped the code in DOM ready:
$(document).ready(function(){
alert($('#mydiv').find('*').length);
});
Upvotes: 3