JQuery selector

dom, jquery

Solution

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

- IDs are expected to be unique, and the path you receive precedes the path you want in the source.

- (less likely in this situation) IDs are expected to begin with a letter

Problem

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> ```

Original source