Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find closest previous element jQuery

Tags:

jquery

I am wanting something similar to this person, except the element I want to match might not be a direct sibling.

If I had this HTML, for example,

<h3>     <span>         <b>Whaddup?</b>     </span> </h3> <h3>     <span>         <b>Hello</b>     </span> </h3> <div>     <div>         <img />     </div>      <span id="me"></span> </div> <h3>     <span>         <b>Goodbye</b>     </span> </h3> 

I would want to be able to do something like this:

var link = $("#me").closestPreviousElement("h3 span b"); console.log(link.text()); //"Hello" 

Is there an easy way to do this in jQuery?

EDIT: I should have made my specification a little bit clearer. $("#me") may or may not have a parent div. The code should not assume that it does. I don't necessarily know anything about the surrounding elements.

like image 696
Peter Olson Avatar asked Aug 10 '11 21:08

Peter Olson


People also ask

How can I find previous siblings in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

What is closest tr in jQuery?

jQuery closest() Method The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on.

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.


2 Answers

var link = $("#me").closest(":has(h3 span b)").find('h3 span b'); 

Example: http://jsfiddle.net/e27r8/

This uses the closest()[docs] method to get the first ancestor that has a nested h3 span b, then does a .find().

Of course you could have multiple matches.


Otherwise, you're looking at doing a more direct traversal.

var link = $("#me").closest("h3 + div").prev().find('span b'); 

edit: This one works with your updated HTML.

Example: http://jsfiddle.net/e27r8/2/


EDIT: Updated to deal with updated question.

var link = $("#me").closest("h3 + *").prev().find('span b'); 

This makes the targeted element for .closest() generic, so that even if there is no parent, it will still work.

Example: http://jsfiddle.net/e27r8/4/

like image 76
user113716 Avatar answered Sep 20 '22 01:09

user113716


see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b"); alert(link.text()); 

see http://jsfiddle.net/gBwLq/

like image 29
Emil Avatar answered Sep 20 '22 01:09

Emil