I'm doing some quite rudimentary jQuery stuff, getting started really, and I'm frequently navigating up the dom by doing things like
$(this).parent().parent().addClass('hello');
I was just wondering if there's a nicer way to do this?
You can use parents
, which returns all ancestor elements in turn. If you want to stop traversing at a particular level, use eq
to filter the resulting collection. For example, to get the grandparent:
// 0 = parent, 1 = parent of parent, etc.
$(this).parents().eq(1).addClass('hello');
If you want to go upwards through the tree and stop not at a particular level, but at a particular selector match, use closest
instead, eg:
$(this).closest("table").addClass('hello');
您可以使用closest()
方法,该方法返回与祖先链中给定选择器匹配的第一个元素。
$(this).closest(SELECTOR_OF_THE_PARENT).addClass('hello')
Say you have the following HTML:
<div>
<span>
<strong>Hi there</strong>
</span>
</div>
You could just use .parents()
to get the div
element:
$("strong").parents("div").addClass("hello");
Simply replace "strong"
with this
and you can use a selector to find a specific parent element.
听起来像你的.parents()
或.closest()
- 后者是最有效的,因为它一旦匹配最近的选择器就停止进展DOM。
"I was just wondering if there's a nicer way to do this?"
It's definitely a great idea to be intimately familiar with jQuery's selection and traversal methods.
However, if in the future you find yourself overwhelmed by traversal and discover:
...it might be time to consider a formal model - view approach .
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.