开发者

jQuery - is there better syntax than "parent().parent().parent()"

开发者 https://www.devze.com 2023-04-04 21:10 出处:网络
I\'m doing some quite rudimentary jQuery stuff, getting started really, and I\'m freque开发者_JAVA技巧ntly navigating up the dom by doing things like

I'm doing some quite rudimentary jQuery stuff, getting started really, and I'm freque开发者_JAVA技巧ntly 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, e.g.:

$(this).closest("table").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.


You can use the closest() method, which returns the first element that matches the given selector in the ancestor chain.

$(this).closest(SELECTOR_OF_THE_PARENT).addClass('hello')


Sounds like your after .parents() or .closest() -- the latter being the most efficient, as it stops progressing up the DOM once it matches the closest selector.


"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:

  1. That your "data model" is actually contained in your DOM
  2. Maintaining and changing applications of this nature is very painful

...it might be time to consider a formal model-view approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消