TheNone
TheNone

Reputation: 5802

Closest element and prev()

I want to addClass to closest p in click event:

http://jsfiddle.net/d7gFf/2/

But this couldnot add or remove class to p element. What is wrong with click event.

Thanks in advance

Upvotes: 1

Views: 1160

Answers (3)

BoltClock
BoltClock

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

Phil.Wheeler
Phil.Wheeler

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

Brad Christie
Brad Christie

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

Related Questions