How to get the nearest parent node given a text node in jQuery?
Assuming I have a sele开发者_Python百科ctor for a text node in jQuery, how can I get the parent node?
Any element or text node is a Node
, which has a parentNode
property. You don't need jQueryfor this but you can turn the parent into a jQuery object:
$(textNode.parentNode)...
$('selector_for_your_textnode').parent()
for a jQuery object, or
$('selector_for_your_textnode').parent()[0]
for a regular DOM object.
You might also use .closest('element_you_want')
for more flexibility.
As cletus points out in comments, if you want to grab an actual textNode and work upward from there, things do get a bit dicier than a vanilla jQuery selector. It can be done, but you have to look for nodeType 3. This answer may help with that part.
jQuery offers a few options to do this. The most basic one is:
$(selector).parent();
This will return the immediate parent node of the selected element (or the parent of each element in the set if the selector matches more than one).
The next option is:
$(selector).parents();
For each element in the matching set, this will return all parents (and grandparents, great grandparents, etc.) of that element, up to and including the root node of the document (<html>
for HTML documents). You can pass this a selector to only get elements that match., e.g.
$(selector).parents('div'); // only parents that are divs
The final way is to use:
$(selector).closest(otherSelector);
This is a little different, because it will return the first element to match the second selector, starting at the calling set. So if I have this:
<div>
<ul>
<li>
<p id="foo">foo</p>
</li>
</ul>
</div>
and I do $('#foo').closest('p')
, I will get back a jQuery set containing the p#foo
. If I instead do $('#foo').closest('ul')
, I will get back the <ul>
element, as you would expect.
you mean like
$('.myselector').parent(); ?
精彩评论