简体   繁体   中英

Selecting a nested element by id or class with jquery

I'm a bit confused how jquery searches through the DOM. Does it select from the root node, similar to XPath / selector, or from the current no matter where they are, similar to XPath // selector?

I have the following setup:

<body>
    <div id="contentSection">
    //A bunch of nested DIVs follow
           <div id="parentDIV">
                <span>Selector1</span>
                <select class="selector" id="first">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>                
                </select>

                <span>Selector2</span>
                <select class="selector" id="second">
                    <option value="A">A</option>
                    <option value="B">B</option>
                    <option value="C">C</option>                
                </select>
          </div>
    </div>
    <div id="someOtherDIVs> </div>
    <div id="someOtherDIVs> </div>
  </body>

Now if I try to select the content section first, then filter by class or id, I can attach an event handler to the select element, but if I try to query the element directly, the event handler is never attached.

For example, this works:

$('#contentSection').change('.plotSelector', function(e)

But these do not:

$('#first').change(function(e) ... 
$('.selector').change(function(e) ...

Can someone explain why? Is there a way to select from the root any element anywhere in the DOM?

Using jquery 2.1.1

Yes the selectors work across the DOM ( http://api.jquery.com/category/selectors/ )

The fiddles supplied in the comments work, have you checked your console for errors, maybe the javascript isn't running completely.

Is there a way to select from the root any element anywhere in the DOM?

So long as you start from document. , the standard javascript methods all select from the root:

  • document.getElementById('');
  • document.getElementsByClassName('');
  • document.getElementsByTagName('');
  • document.querySelector('');
  • document.querySelectorAll('');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM