Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Select children with $(this)

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
});
like image 954
Khang Nguyen Avatar asked Mar 06 '26 05:03

Khang Nguyen


1 Answers

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.

like image 188
Pointy Avatar answered Mar 07 '26 18:03

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!