River CR Phoenix
River CR Phoenix

Reputation: 311

Select a child with a given class

I have three similar sections. I want to select an element with a given class but only within the scope of the element I clicked.

My current code selects all the elements with the same class.

If I add an event handler on class mine, and some action needed to be done on target class, only for the inner2 within the scope of class one I clicked, so how do i do it.

HTML:

<div class="one">
 <div class="some">
      <div class="mine"></div>
  </div>
 <div class="inner1">
 </div>
 <div class="inner2">
   <div class="target"></div>
 </div>
</div>

<div class="one">
  <div class="some">
      <div class="mine"></div>
  </div>
  <div class="inner1">
  </div>
  <div class="inner2">
     <div class="target"></div>
  </div>
  </div>

Upvotes: 3

Views: 78

Answers (4)

Nishit Maheta
Nishit Maheta

Reputation: 6031

use below code . use find to search child element

$('.one').on('click',function(){
   var inner2Obj = $(this).find('div.inner2');
   inner2Obj.slideToggle(function(){
      // your code
   });
   console.log(inner2Obj) // this will log inner2 object within clicked one DIV
});

Upvotes: 2

ozil
ozil

Reputation: 7117

use sibling

$(".mine" ).click(function() {  
$(this).siblings('.inner2').slideToggle(function(){
if(temp==0){
    $(this).closest(".proElement").addClass('darkBg');
    temp=1;
}
else{
    $(this).closest(".proElement").removeClass('darkBg');
    temp=0;
}
});
});

demo

Upvotes: 2

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can also use .siblings() here:

$(".mine" ).click(function() {  
$(this).siblings('.inner2').slideToggle(function(){
if(temp==0){
    $(this).closest(".proElement").addClass('darkBg');
    temp=1;
}
else{
    $(this).closest(".proElement").removeClass('darkBg');
    temp=0;
}
});// end of slideToggle
}); // end of click

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : you can make use of siblings() to get inner2 element and do your operation on it.

$(".mine" ).click(function() {  
   $(this).siblings('.inner2').slideToggle(function(){
      if(temp==0){
        $(this).closest(".proElement").addClass('darkBg');
        temp=1;
     }
    else{
       $(this).closest(".proElement").removeClass('darkBg');
       temp=0;
      }
   });// end of slideToggle
}); // 

Upvotes: 3

Related Questions