问题
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
回答1:
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('');
回答2:
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.
来源:https://stackoverflow.com/questions/40871619/selecting-a-nested-element-by-id-or-class-with-jquery