Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nearest ancestor node in jQuery

In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)". Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top? For the moment I use this utility function:

function ancestor(elem, selector) {
  var $elem = $( elem ).parent();
  while( $elem.size() > 0 ) {
    if( $elem.is( selector ) ) 
    return $elem;
    else
       $elem = $elem.parent();
  }
  return null;
}

Can someone tell me if there is a clever way to do the job?

like image 797
Pier Luigi Avatar asked Oct 14 '08 14:10

Pier Luigi


People also ask

How do I get the closest div using jQuery?

The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.

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.

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

How do you use the closest function in JavaScript?

The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.


2 Answers

Edit: Since jQuery 1.3, this has been built in as the closest() function. eg: $('#foo').closest('.bar');


yep - parents() traverses up the tree.

<div id="a">
    <div id="b">
        <p id="c">
            <a id="d"></a>
        </p>
    </div>
</div>

$('#d').parents("div:first"); will select div b.

like image 152
nickf Avatar answered Oct 01 '22 14:10

nickf


Adding to @nickf's answer:

jQuery 1.3 simplifyed this task with closest.

Given a DOM:

<div id="a">
    <div id="b">
        <p id="c">
            <a id="d"></a>
        </p>
    </div>
</div>

You can do:

$('#d').closest("div"); // returns [ div#b ]

[Closest returns a] set of elements containing the closest parent element that matches the specified selector, the starting element included.

like image 30
2 revs Avatar answered Oct 01 '22 15:10

2 revs