JQuery - select children with $ (this)

I am trying to count the number of children inside a div using the jQuery selector $(this)and element class. And the results are different. I thought jQuery $(this)refers to the object of the owner of the object, is there something special in $(this)that I am missing?

$('.parent').ready(function(){
        $('.parent').children().length; // 6
        $(this).children().length; // 1
});
+3
source share
2 answers

It:

    $('.parent').children().length; // 6

is the right way to do this. It:

    $(this).children().each(function().length; // 1

is a syntax error. If you really want to iterate through children, you can use ".each ()", but you will need to do it correctly:

    $(this).children().each(function() {
      var $child = $(this);
      // ...
    });

Note that inside the callback, ".each ()" thiswill refer to each child element sequentially, since the function is called by jQuery.

+5

$(this) $('.parent').ready() $('.parent').

$(this) each() children() .

, ( - ):

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

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

: : 6 parent, . , , :

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

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

Source: https://habr.com/ru/post/1794942/


All Articles