| Author |
Question about jQuery :first selector
|
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2542
|
|
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
Joined: Mar 25, 2001
Posts: 1721
|
|
: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
Joined: Jan 10, 2002
Posts: 56224
|
|
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.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56224
|
|
|
This likely means I'll need to beef up the description of this and related filters in the 3rd edition.
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2542
|
|
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.
|
 |
 |
|
|
subject: Question about jQuery :first selector
|
|
|