Bug Tracker

Opened 15 years ago

Closed 15 years ago

Last modified 14 years ago

#2631 closed bug (invalid)

Something wrong with :last-child

Reported by: chrishandorf Owned by:
Priority: major Milestone: 1.2.4
Component: core Version: 1.2.3
Keywords: Cc:
Blocked by: Blocking:


Something must be wrong with the jQuery ":last-child" selector. In my program this expression returns an empty object:

var newObject = $("#rootFolder:last-child");

But if I simply change the code to this it works fine:

var newObject = $("#rootFolder").children(":last-child");

Change History (3)

comment:1 Changed 15 years ago by davidserduke

Resolution: worksforme
Status: newclosed

If I understand it all correctly, those 2 you listed are the same.


looks at all the children of element with id="rootFolder" and returns the last one


gets the element with id="rootFolder" and filters it to see if it is the last child. So

  <div id="rootFolder"></div>

will return no items for that. It is equivilent to



If I'm misunderstanding, then feel free to reopen the ticket with an actual test case (including html markup) which shows the problem.

comment:2 Changed 15 years ago by chrishandorf

Resolution: worksforme
Status: closedreopened

OK - here is the HTML that demonstrates the problem. It will output "test1=0 test2=1" when it seems like they should both be set to "1":

   <div id="rootFolder">
      <div class="test"></div>
   <div class="log">
<script src="jquery-1.2.3.js" type="text/javascript"></script>
<script type="text/javascript">
   var test1 = $("#rootFolder:last-child");
   var test2 = $("#rootFolder").children(":last-child");
   $(".log").append("test1="+test1.length+" test2="+test2.length+"<br>");

comment:3 Changed 15 years ago by scott.gonzal

Resolution: invalid
Status: reopenedclosed

You are using the selector incorrectly. As David has pointed out, "#rootFolder:last-child" will first find #rootFolder, then filter it based on whether or not is is the last child of its parent. What you want is "#rootFolder > :last-child" Which will find #rootFolder, then all its children, then filter the children down to the last child (equivalent to test2).

Perhaps it will help you to think about the context in which all the ":" selectors are applied. For example, ":parent" will filter the current elements based on whether or not they are parents; it won't find the parents of the current elements.

Note: See TracTickets for help on using tickets.