I need to get the first parent that has position:relative
. Something like in the example below but my real content will be dynamically generated.
<div id="parent1" style="position:relative">
<div id="parent2">
<div id="my-element" style="position:absolute"></div>
</div>
</div>
Do you know a simple way to do this using 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.
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.
jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
You can filter
the set of parents()
, and grab the first element matching your filter:
$('#my-element')
.parents()
.filter(function() {
return $(this).css('position') == 'relative';
}).first();
Demo (Works with classes, too)
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