javascript - is(':first') returns different (wrong?) results for what should be the same element. jsFiddle inside -


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

given html of only

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

and 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 $(e.currenttarget).parent().is('li:first') false?

after step debugging through jquery code ran, turns out issue way jquery() method used within is() method. know, you can pass context method, , internally, context being used is() method (and being set differently various selectors).

when $(e.currenttarget) used, context set button triggered event. while when $('button') used, context set document object. makes sense when think of how these selectors need scoped.

here relevant part of is() method:

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

based on that, when run $(e.currenttarget), call jquery() method evaluation to:

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

which returning -1, , reporting false


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -