monda
monda

Reputation: 3915

Select element two level up in jQuery

<p class="align-with-btn">
  <a class="with-icon add-new-line" id="add-line" href="#add-new-line">
    <i class="icon-add-inv"></i>Add Reference
 </a>
</p>
<div class="row update-button">
  <div class="span4">
   <button class="submitAesReference loadRef btn" id="submitReference">
      <i class="icon-submit"></i>Submit  Reference
   </button>
  </div>
</div>

Here i want to select hide link with class name "add-new-line" when i click on the button below

i tried

var button = $(this);
button.closest('.span4').parent().closest('.add-new-line').hide();

but its not working ?

Upvotes: 1

Views: 644

Answers (4)

Andy
Andy

Reputation: 30135

.closest only iterates through the parents of the element but .add-new-line isn't a parent of .row. So you'll have to do something like

button.closest('.row').prev().find('.add-new-line').

Or you wrap your p.align-with-btnand div.row into another element, for example div.wrapper. then you could do:

button.closest('.wrapper').find('.add-new-line')

That way you don't have to need to use .prev() which can break easily, if you introduce new elements.

Upvotes: 2

semir worku
semir worku

Reputation: 120

First select the row parent of the button and then find its siblings (p) and then find the a tag inside the p tag.

$('button').parents('.row').siblings('p').find('a.add-new-line').hide();

hope this helps.

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

I see that your .add-new-line element also has an ID. Why not just use that?

$('#add-line').hide();

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to find the previous element of current button's parent .row element

button.closest('.row').prev().find('.add-new-line').hide();

Upvotes: 1

Related Questions