Bernardo Baalen
Bernardo Baalen

Reputation: 129

closest() traversing not working in my case

I want to use closest to traverse select an item, my html as below :

<span id='target'></span>
<a></a>

jquery

assume 'a' = $(this),
then I do $(this).closest('#target');

but it seem it doesn't select the #target.. what's wrong here?

Upvotes: 0

Views: 73

Answers (3)

Vlad Skyikov
Vlad Skyikov

Reputation: 36

Closest('#target') isn't going to work here since the a tag is a sibling to span#target not a parent. Use Closest to find the parent element for both of these and then do a find to get your target span, or just use .prev to get sibling target span.

$(this).closest("div").find("#target");

or

$(this).prev("#target");

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Closes does not check siblings, it check element and its parents jQuery.closest

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

In your case <a> and <span> are siblings, not parent/child - so using closest will not find span starting from a.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Since you have and id, you can use it as an id-selector because id will be unique in a document - there is no need to use any relational lookup in this case.

var target = $('#target')

If you have a pattern like above where a anchor element is followed by a span element then use a class attribute instead of id. In such a case the span is the previous sibling of the anchor element so you need to use .prev().

<span class='target'></span>
<a></a>

var target = $(this).prev('.target');// $(this).prev() is sufficient 

.closest() will look for an ancestor element, not for a sibling.

Upvotes: 1

Related Questions