captainrad
captainrad

Reputation: 3830

Toggle css of 1 of multiple classes of the same name

I have dynamically created divs..

<div class="container"></div>

Each div has an input element within it..

<div class="container">
   <input type="button" class="container_button" value="toggle" />
</div>

My goal is to minimize only the container div of the button clicked..

$('.container_button').onclick(function() {
   $('.container').css('height','20px');
});

How can I achieve this when multiple divs of the same class exist?

Upvotes: 2

Views: 312

Answers (2)

Ram
Ram

Reputation: 144689

jQuery object doesn't have onclick method, you can use on method instead, as you are generating the element dynamically you should also delegate the event.

$(document).on('click', '.container_button', function() {
   $(this).parent('.container').css('height','20px');
   //  ^--- clicked element
});

Upvotes: 1

Matt Huggins
Matt Huggins

Reputation: 83279

You need to find .container relative to the DOM element that was clicked.

$('.container_button').click(function () {
   $(this).closest('.container').css('height', '20px');
});

Upvotes: 1

Related Questions