Is (': first') returns different (wrong?) Results for what should be the same element. jsFiddle inside

http://jsfiddle.net/garnwraly/sfrwU/2/

given HTML only

<li> <button id="bam">click</button> </li> 

and this script

 $('body').on('click', 'button', function (e) { //console.log( e.currentTarget == $('button')[0] ); //true; //console.log($('li').is('li:first')); //true console.log($(e.currentTarget).parent().is('li:first')) //false console.log($('button').parent().is('li:first')); //true console.log($($('button')[0]).parent().is('li:first')); //false }); 

why is $(e.currentTarget).parent().is('li:first') false?

+6
source share
2 answers

After debugging the code through jQuery code, when it is run, this turns out to be a problem with how the jQuery() method is() used in the is() method. As you know, you can pass a context to a method , and internally this context is used with the is() method (and differently for different selectors).

When $(e.currentTarget) , the context is set to the button that triggers the event. If $('button') , the context is set to the Document object. This makes sense when you think about how these selectors should be covered.

Here is the relevant part of the is() method:

 jQuery( selector, this.context ).index( this[0] ) >= 0 

Based on this, when launched as $ (e.currentTarget), the jQuery() method call is evaluated as follows:

 jQuery("li:first", "button#bam").index( this[0] ) >= 0 

Obviously, it returns -1 and reports false

+4
source

I think it may be that :first only cares about the match - in the case when the jQuery object is created from the DOM element, the selection is not negotiated. note that

 console.log($(document.getElementById('bam')).is(':first')); 

also logs false .

I donโ€™t feel that the behavior is correct and the error should probably be logged, but even if it works correctly, I donโ€™t think in this case testing :first really benefits. If you use .parent() to navigate through the DOM to the parent node, starting with one element, then it makes no sense to ask if the parent is the first element - there will always be a parent (except for the DOM root from the course), and always only one.

If you do this with :first-child , which is really interesting, but not necessarily relevant, then it works as you would expect, because :first-child is actually about the DOM structure. The :first qualifier is only the first matching element.

+3
source

All Articles