Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery chaining parent(), is there an easier way?

Hay, I have some markup like this

<div id="some-id">
    <h2><a href="#">Title</a></h2>
</div>

and some jQuery like this

$(this).parent().parent().attr("id")

$(this) is referring to the 'a' tag within the 'h2'

Is there an easier way to select the parent div without using parent() twice. I tried

$(this).parent("div").attr("id")

but it didn't work.

Thanks

like image 400
dotty Avatar asked Oct 13 '10 09:10

dotty


People also ask

What is parent() in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How to get parent element with jQuery?

The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element. Here selector is the selected elements whose parent need to find.

What does $( Div parent select?

The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.

What is parent and child in jQuery?

The parent > child selector in jQuery is used to select all elements that are a direct child of the specified element.


1 Answers

You can use .closest(), like this:

$(this).closest("div").attr("id")

You can test it here. .parent("div") isn't as intuitive as it seems, it gets only the immediate parent if it matches the selector, .closest() climbs the parents until it matches the selector.

Please note that (doesn't apply to this example) if this matches the selector, it returns that element, it doesn't start with the first parent, it starts with itself.

like image 146
Nick Craver Avatar answered Sep 23 '22 16:09

Nick Craver