Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first parent that has a certain CSS property using jQuery?

Tags:

jquery

css

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?

like image 307
Victor Avatar asked Mar 04 '13 13:03

Victor


People also ask

How do I find a specific 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.

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.

Where can I find grandparents in jQuery?

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.

How can I get next sibling in jQuery?

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.


1 Answers

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)

like image 170
David Hedlund Avatar answered Sep 28 '22 15:09

David Hedlund