Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery selector

Tags:

jquery

dom

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>
like image 671
mysomic Avatar asked Feb 26 '26 19:02

mysomic


1 Answers

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
like image 121
Matt Hampel Avatar answered Mar 01 '26 10:03

Matt Hampel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!