Reputation: 5802
I want to addClass to closest p in click event:
But this couldnot add or remove class to p element. What is wrong with click event.
Thanks in advance
Upvotes: 1
Views: 1160
Reputation: 723568
closest()
searches ancestors, not siblings. Remove it, prev()
will find the previous sibling <p>
for you (you can always pass in the p
selector to ensure it only selects the previous paragraph):
$(this).prev("p").toggleClass("showComment");
Upvotes: 3
Reputation: 16848
You don't need both .closest() and .prev() to get this to work.
$('.cnt').bind("click", function (e) {
$(this).prev().toggleClass("showComment");
});
Upvotes: 0
Reputation: 101604
That's because closest
navigates up the tree. Since the .cnt isn't inside the paragraph, this won't work. You are probably looking for just the previous paragraph, such as:
$(e.target).prev("p").toggleClass("showComment");
Upvotes: 2