Bruce Lim
Bruce Lim

Reputation: 755

jQuery .is() :first showing different behavior from :last

Can anyone explain to me what the heck is going on with the jQuery .is() function?

I have a situation where I'm checking to see if an element is the first of a group of elements that I have selected.

<div>
   <ul>
      <li>first</li>
      <li>second</li>
      <li>third</li>
      <li>last</li>
   </ul>
</div>

$('div > ul > li').first().is(':first') or
$('div > ul').find('li:first').is('li:first') 

returns false.... what is going on here?

$('div > ul > li').last().is(':last') or
$('div > ul').find('li:last').is('li:last') 

return true

Upvotes: 2

Views: 131

Answers (2)

Won
Won

Reputation: 1805

Look at http://jsfiddle.net/MvWcv/1/ When you select ':first', it means that you select the FIRST NODE OF WHOLE DOCUMENT. ':last' is also pointing the last node of whole document, which is "last".

Thus it should be

$('div > ul > li').first().is('div > ul > li:first')

and

$('div > ul > li').last().is('div > ul > li:last')

Upvotes: 1

pimvdb
pimvdb

Reputation: 154908

The selector :first just selects the first element from all elements on the page. That one is <html>, try running $(":first"). :last works in your case because the last <li> also happens to be the last element on the whole page.

You might want :first-of-type or :first-child instead.

Upvotes: 5

Related Questions