Reputation: 224
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>
<div class="<span class="tm bg-win blue">tm card</span>">
<span class="tm lightyellow">...</span>
</div>
</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]]
Upvotes: 0
Views: 1795
Reputation: 385
.closest() traverses upwards in the dom, and therefore it will never reach the code element. If you have to use $(this) to find the code element you can do the following:
$('.js-show-code').click(function(){
$(this).parent().siblings().find('code').slideToggle();
});
OR do it like this (wrap the whole thing in a container):
<div class="container">
<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>
<span class="tm bg-win blue">tmcard</span>
<span class="tm lightyellow">...</span>
</code>
</div>
</div>
$('.js-show-code').click(function(){
$(this).closest('container').find('code').slideToggle();
});
Upvotes: 0
Reputation: 126
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
Upvotes: 2
Reputation: 29693
.closest
is used to find closest
parent of respective element
. Your button is wrapped inside a h2
element and closest
to that button
would be h2
and hence navigating in reverse direction of parents
. You have wrong understanding about how .closest
works. What you need to do is, navigate to h2
with closest('h2')
and get its next
element and find
required code
element as per present DOM
structure you have. Below is the snippet
.
$('.js-show-code').click(function() {
$(this).closest('h2').next().slideToggle()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
<div class="<span class="tm bg-win blue">tm card</span>">
<span class="tm lightyellow">...</span>
</div>
</code>
</div>
Upvotes: 2