Aug 18, 2017

JQuery find() vs children() vs filter()

For HTML:

<div id="level1">
<span id="spanL1">L1</span>
<div id="level2">
<span id="spanL2">L2</span>
<div id="level3">
<span id="spanL3">L3</span>
Dummy
</div>
</div>
</div>
: this code:

$('#level1').on('click',function(event){
console.log("level1 click");
$(this).children('span').hide();
});

; will hide only L1 since it is first child of Level1 div.

If instead we use:

$(this).find('span').hide();

; all spans will be hidden.

Filter on the other hand is applied only to already found set of elements.

For example:

$(this).filter('span').hide();

; can't work since filter is applied on single DIV element.
This will work:

$(this).find('span').filter(':first').hide();

Alternative and probably more used is using filter as item iterator :

$(this).find('span').filter(function(index){
console.log($(this).text());
});
});

No comments:

Post a Comment