Khang Nguyen
Khang Nguyen

Reputation: 63

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

Upvotes: 3

Views: 1362

Answers (2)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

$(this) inside the $('.parent').ready() method refers to $('.parent') object.

$(this) inside the each() method of the children() collection refers to the current child iterated.

So the way to achieve same number (for whatever reasons you have) is:

$('.parent').ready(function(){
   var directLength = $(this).children().length; // 6
   var indirectLength = 0;
   $(this).children().each(function(){
      indirectLength++;
   });

   alert([directLength, indirectLength].join("\n"));
});

Edit: your comments can have only one meaning: you have 6 elements with class parent and each of those have only one child. So I assume you're want to count the parent elements, here is proper code for this:

$(document).ready(function() {
   var directLength = $('.parent').length; // 6
   var indirectLength = 0;
   $('.parent').each(function() {
      indirectLength++;
   });

   alert([directLength, indirectLength].join("\n"));
});

Upvotes: 0

Pointy
Pointy

Reputation: 413996

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.

Upvotes: 5

Related Questions