tags:

views:

259

answers:

4
+2  Q: 

JQuery selector

Given the following unordered list, the JQuery selector $("#root #2") selects:

/ul/li/ul[@id='root']/li/ul[@id='1']/li/ul[@id='2']

Whereas I would have expected it to select the shorter path:

/ul/li/ul[@id='root']/li/ul[@id='2']

Anyone any ideas?

<ul>
    <li>root
     <ul id="root">
      <li>1
       <ul id="1">
        <li>2
         <ul id="2"> <!--*selecting this*-->
          <li>3<ul id="3"></ul></li>   
          <li>4<ul id="4"></ul></li>
         </ul>
        </li>
        <li>3<ul id="3"></ul></li>
       </ul> 
      <li>2
       <ul id="2"> <!-- *expecting this* -->     
        <li>3
         <ul id="3"> 
          <li>4<ul id="4"></ul></li>
         </ul>
        </li>
       </ul>
      </li>
      <li>3<ul id="3"></ul></li>
      <li>4<ul id="4"></ul></li>
     </ul>
    </li>
</ul>
+10  A: 

Two reasons why the behavior might be undefined / not what you expect:

  1. IDs are expected to be unique, and the path you receive precedes the path you want in the source.
  2. (less likely in this situation) IDs are expected to begin with a letter
Matt Hampel
+3  A: 

Using a space in a selector selects any ancestor. My hunch is that since the li with id=2 comes before the ul with id=2 in the DOM, jQuery stops at that (since id's are expected to be unique).

I hope this isn't real HTML... because id's should really be unique.

womp
+1  A: 

You're using a descendant operator, which will search all descendants. I imagine that jQuery uses depth first search algorithm in searching the DOM tree. That explains why you get the longest one first. As for why jQuery only returns one node, you're using ID selector, which is supposed to be unique in all DOM node. I would expect jQuery to return after the first match, as there's no point in traversing the rest of the tree.

Salamander2007
+1  A: 

This selector should return any element with an ID of 2 which is a descendant of any element with an ID of root, in DOM order. I'd expect it to return both of the elements you mentioned in your question. The deeper one will be first because it's first in the document.

Note that IDs should be unique. It is an error to have two elements with an ID of 2.

Sidnicious