Rhythem Aggarwal
Rhythem Aggarwal

Reputation: 356

Jquery help regarding hiding selected div divs

i have say five divs with the layout as in the following code..

//Div one
<div class="container">
<div class="hide">
    <button class="hide" value="hide" />
</div>
</div>

//Div Two
<div class="container">
<div class="hide">
    <button class="hide" value="hide" />
</div>
</div>

//Div Three
< div class="container">
<div class="hide">
    <button class="hide" value="hide" />
</div>
</div>

now say i click the hide button in the second div, i want to hide the second div.. That is i want to hide the div corresponding to the button click.. How to do that via jquery only???

i tried using the 'this' keyword through jquery but that would hide all the containers and not just one. please help me

Upvotes: 0

Views: 58

Answers (2)

nbrooks
nbrooks

Reputation: 18233

Use the jQuery .closest() method to traverse up the DOM tree to target the <div>. Then you can trigger the hide on the div.

$('button.hide').click(function() {
    $(this).closest('.container').hide();
});

This, of course, is done on DOM ready: $(document).ready(function() { /*...*/ });

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

$('button.hide').on('click', function() {
   $(this).closest('.container').hide()
});

I specified button.hide instead of .hide as selector, because you have more different elements with that classname

See closest() usage on jQuery docs

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

Upvotes: 2

Related Questions