Sam Swift 웃 Sam Swift 웃 - 7 months ago 29
Javascript Question

Why isn't jQuery closest working

I am working on a small system that uses collapsable blocks - for this I am have a css class that toggles on or off depending on the jQuery dependancy.

The code I am using is:

$("#click_me").on("click", function () {
$("#clicked_action").toggleClass("show");
});


And this works, but is not what is needed. What is need is:

$(".collapse-header").on("click", function () {
$(this).closest(".collapse-body").toggleClass("show");
});


But this does not work.

I am not getting any console errors, so any help is apprecated

EDIT HTML value:

<div class="collapse-header" id="click_me">
<span class="float-left">Click me</span>
<span class="float-right"><span class="glyphicon glyphicon-plus"></span></span>
<hr class="hr" />
</div>
<div class="collapse-body" id="clicked_action">
I'm collapsed
</div>

GG. GG.
Answer

You are looking for

$(this).parent().find(".collapse-body")

About .closest

$(element).closest(selector) is to find the first element which matches selector in traversing up through element's ancestors.

In your case, your elements are at the same level ("siblings") so .closest doesn't work.

Comments