Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about jQuery :first selector

 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm running through the jQuery Selector Lab Page from Bear's jQuery In Action, 2nd Ed.. (Source available here: http://www.manning.com/bibeault2/jqia2.source.zip ) Basically, the right half of the page is a sample web page, and the left half lets you type in jQuery selectors that draw red boxes around the content they match in the right half.

The sample page contains an unordered list, with two list items, each of which itself contains an unordered list with multiple items. So something like:



When I type in a selector "li li", I get all six fruits and vegetables highlighted as I expected, but when I type in "li li:first", I only get "Apple". The selector "li li:nth-child(1)" though gives me both "Apple" and "Asparagus". Is this a jQuery bug, or am I thinking of it wrong?
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1820
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
:first matches a single element. So "li li:first" is giving you the first "li" that is a descendant of an "li".

To get elements that are the first child of their parent, you can use :nth-child(1), as you pointed out, or :first-child.

http://api.jquery.com/first-selector/
http://api.jquery.com/first-child-selector/
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65118
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Magic Mike is correct.

Another way to think of it is to envision that the base selector creates a set of matching elements; the :first filter then selects the first of that set. So it will always result in a single match.

:first has nothing at all to do with order within the DOM, but order within the matched set.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65118
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This likely means I'll need to beef up the description of this and related filters in the 3rd edition.
 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, well, descriptions can never be so beefy that some moron somewhere still won't misread them. I didn't even notice there were both :first and :first-child filters.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic