I try to count the number of children inside a div using jquery $(this) selector and the element's class. And the results are different. I thought jquery's $(this) refers to the owner object of function, is there any thing special about $(this) that I am missing?
$('.parent').ready(function(){
$('.parent').children().length; // 6
$(this).children().length; // 1
});
This:
$('.parent').children().length; // 6
is the correct way to do it. This:
$(this).children().each(function().length; // 1
is a syntax error. If you really wanted to iterate through the children you could use ".each()" but you'd have to do it properly:
$(this).children().each(function() {
var $child = $(this);
// ...
});
Note that inside the ".each()" callback, this will refer to each child in succession as the function is called by jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With