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
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.
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.
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.
The parent > child selector in jQuery is used to select all elements that are a direct child of the specified element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With