Selecting only 1 div ( current div inside parent which fires action )

Hello,
i have three div’s and every div has hidden child (display none)
when i write:

$(‘.link img’).click(function() {
$(‘.hidden’).css({‘display’:‘block’})
});

Something like this works, but then ALL .hidden appears, and i want to show only .hidden that is in clicked img. (current hidden not all hidden )

<div class="link"><p>show menu</p>
  <a href="#"><img src="images/icons/arrow.png" /></a>
  <div class="hiddenDiv"></div>
</div>

<div class=“link”><p>show menu</p>
<a href=“#”><img src=“images/icons/arrow.png” /></a>
<div class=“hiddenDiv”></div>

&lt;/div&gt;   &lt;div class="link"&gt;&lt;p&gt;show menu&lt;/p&gt;
  &lt;a href="#"&gt;&lt;img src="images/icons/arrow.png" /&gt;&lt;/a&gt;
  &lt;div class="hiddenDiv"&gt;&lt;/div&gt;
&lt;/div&gt;

Thanks for help, because i have all the time problems with wthis approach, where ia want to select current item not all items.

Can u explain me how it works, i dont need ready solutions, but explanation…

THANK You all for any help.

Mike.

In your click handler you do:


$(".hidden").css({"display":"block"});

Which targets all elements that have that class. If you only want to target the ones that fall inside the .link div you’d have to find the .link div, and then find the .hidden div within it.

Sounds hard, but thankfully jQuery makes this really easy for us. It’s hard to completely convey all of this without a proper example, so I’ve commented this code to show you what’s happening.


//change the selector so you're targeting the <a> instead
$(".link a").click(function(e) { //using the event variable passed in to the handler
  e.preventDefault(); //prevent default click event from happening on the link


  // "this" inside of a jQuery event handler references the element that the event came from

  // .closest() goes up the tree and finds the first matching item based on the selector you passed in

  // .show() is jQuerys built in method to apply display:block (there is also .hide() and .toggle())
  $(this).closest(".link").find(".hidden").show();
});

Hope this helps :slight_smile: