Maloke Maloke - 10 days ago 5
Javascript Question

closest() not selecting the element

HTML

<h2 class="tm section-title margin-l-10">Normal Cards<button class="tm bg-dark btn-tiny margin-b-10 float-r js-show-code">show code</button></h2>
<div class="grid-100">
<code>
&lt;div class=&quot;<span class="tm bg-win blue">tm card</span>&quot;&gt;
<span class="tm lightyellow">...</span>
&lt;/div&gt;
</code>
</div>


JAVASCRIPT (jQuery)

$('.js-show-code').click(function(){
$(this).closest('code').slideToggle()
});


I'm still learning Javascript and Jquery, and I have no clue what i'm doing wrong. I can't select the
<code>


It always returns:
[prevObject: r.fn.init[1]]

Answer

closest() get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. You are looking for an element which is not related with button.js-show-code.

Try

 $('.js-show-code').click(function(){
      $(this).closest('h2').next(".grid-100").find("code").slideToggle()
    });

Here is the fiddle