Sebb_T
Sebb_T

Reputation: 1

Find "nearest" element of specific type

class="up" is basically just an arrow pointing upwards.

HTML:

 <div class="change_div"> <!-- change password -->
   <div class="change_title">Change Password<i class="up"></i></div>
   <div class="change_content" display="none">
     <div class="change_subtitle">Enter Password</div>
     <input id="pw_old" class="change_input" type="password"></input>
     <div class="change_subtitle">Enter new Password</div>
     <input id="pw_new1" class="change_input" type="password"></input>
     <div class="change_subtitle">Confirm new Password</div>
     <input id="pw_new2" class="change_input" type="password"></input>
     <div class="button_confirm" onclick="checkInput()"></div>
   </div>
 </div>

jQuery:

 $(document).ready(function(){
   $('div.change_title i').click(function() {
     if($(this).hasClass('up')) {
       $(this).removeClass('up');
       $(this).addClass('down');
       $('.change_content').show(); //help is needed here
     } else if($(this).hasClass('down')) {
       $(this).removeClass('down');
       $(this).addClass('up');
       $('.change_content').hide(); //and here
     }
   })
 });

I have 3 divs with the class "change_content" and 3 arrows for them (1 for each div). If I click on the first arrow, I don't want all 3 divs to show/hide, but only the first one. If I click the second arrow, I only want the second div to show/hide..

How can I do this by using a selector?

Upvotes: 0

Views: 479

Answers (2)

adeneo
adeneo

Reputation: 318212

You can find the element using closest and next

$(this).closest('.change_title').next('.change_content').show();

so

$('div.change_title i').on('click', function() {
    $(this).toggleClass('up down')
           .closest('.change_title')
           .next('.change_content')
           .toggle()
});

Upvotes: 2

j08691
j08691

Reputation: 207901

Change

$('.change_content').show()

to

$(this).parent().next('.change_content').show() 

and

$('.change_content').hide()

to

$(this).parent().next('.change_content').hide()

Upvotes: 1

Related Questions