*
The moose likes HTML, CSS and JavaScript and the fly likes Question about jQuery :first selector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Question about jQuery :first selector" Watch "Question about jQuery :first selector" New topic
Author

Question about jQuery :first selector

Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2840
    
  11

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: 1746
    
    2
: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: 60782
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

This likely means I'll need to beef up the description of this and related filters in the 3rd edition.
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2840
    
  11

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about jQuery :first selector
 
Similar Threads
HTML drop downs not working
jQuery -- add remove list item
Automatic Installation of 100+ Open Source Projects for Java Developers
how would i do the following in css
Problem with struts-menu for second level submenu