Carlo Ravelli
Carlo Ravelli

Reputation: 87

jQuery on multiple of the same divs, without using unique ID's?

Problem in short: I'm trying to make a simple show/hide toggle work on just the element you click on, while right now all (13) divs get affected by the function.

Structure of each div looks like this

<div class="selectbox">
    <h5>Title</h5>
    <p>
        Content
    </p>
</div>

With this jquery code

$('.selectbox h5').click(function(){
         $('div.selectbox,p,span').toggle();
         $('.selectbox').toggle();
    });

So right now, the jquery works. But obviously, does its work on every "selectbox" div on the page. How can I make this work on just the element I click on, without using a unique id for every "selectbox" div?

Upvotes: 1

Views: 211

Answers (4)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

$('.selectbox h5').click(function(){
     $(this).parent().find('p,span').toggle(); 
     $(this).parent().toggle(); // this line should probably be removed 
});

Upvotes: 4

Dipak
Dipak

Reputation: 12190

use $(this) -

$('.selectbox h5').click(function(){

  $(this).closest('.selectbox, p, span').toggle();
  //$('.selectbox').toggle();

});

Upvotes: 3

Jonas Stensved
Jonas Stensved

Reputation: 15286

You may use the keyword this in your function, it represents the item that triggered the event. In this case your H5.

$('.selectbox h5').click(function(){
         $(this).closest('.selectbox').toggle();
    });

Upvotes: 2

Jan.
Jan.

Reputation: 1995

Make it simple..

if you want the parent DIV to toggle then just use $(this).parent().toggle(); in your function. p.e.: If you want to work with the <p> in your div you may address it like $('p', $(this).parent()).toggle();

Upvotes: 1

Related Questions