kackleyjm
kackleyjm

Reputation: 595

Search Up DOM from a given element using jquery

In jquery, I'm trying to find a way to search up the dom until it finds the selector. For example.

Provided this structure:

<span data-type="contact" data-filter="4" id="buyer-lookup" class="uneditable-input contact-lookup" data-original-title="" title="">Jeff</span>
<div class="popover">
   <div class="arrow"></div>
   <h3 class="popover-title"><strong>Jeff</strong></h3>
   <div class="popover-content">
      <address style="margin:0;"> MO<br></address>
      <a data-id="70" data-type="contact" class="pull-right edit-contact" href="#">Edit</a>
      <div class="clear"></div>
   </div>
</div>

On click of '.edit-contact' I'd like to search up until I find 'span.contact-lookup'. I can use parent a couple of times to get what I want like below, but is there a cleaner way so that you can just specify $(this).searchUpFunction('span.contact-lookup'); so it would start at this and search up until it finds span.contact-lookup? .prev doesn't seem to search up parents.

$('.edit-contact').click(function(){
       var filter = $(this).parent().parent().prev('span.contact-lookup').data('filter');
       alert(filter);
    });

Upvotes: 3

Views: 1267

Answers (2)

Felix Kling
Felix Kling

Reputation: 816404

If you don't have any information about the ancestor where span.contact-lookup is the sibling of, you can use .parents() [docs] to select all ancestors:

$(this).parents().prev('span.contact-lookup')

This will be less efficient than using .closest() though, since it will traverse the tree up to the root.

Additionally, if there are multiple ancestors with a span.contact-lookup sibling, you will select all of those. In this case you can get the nearest one with .first() or .last(), depending on the order they are selected in (the order will always be the same, I just don't know it off the top of my head).


So: If you can, use .closest, if not, .parents is probably your best bet (apart from writing your own code to traverse the DOM).

Upvotes: 1

Sharlike
Sharlike

Reputation: 1789

Use closest

$('.edit-contact').click(function(){
   contactID = $(this).closest('div.popover').prev().data('contact-id');
   alert(contactID);
});

Upvotes: 1

Related Questions