Cjmarkham
Cjmarkham

Reputation: 9681

jQuery closest() not working on next element in hierarchy

I have the following html structure:

<em class="help fa fa-question-circle text-muted"></em>
<div class="help-wrapper"></div>

And when using the following JS I assumed it would be fine but it doesn't work. No errors or anything, just won't work.

$('.help').on('click', function () {
  $(this).closest('.help-wrapper').fadeToggle(300);
});

Upvotes: 1

Views: 214

Answers (3)

George
George

Reputation: 36784

closest() traverses up the DOM tree, so any matches are ancestors of this.

You need next():

$(this).next('.help-wrapper').fadeToggle(300);

Upvotes: 3

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

Closes traverses the tree up, it does not work on siblings In your case you can use

$(this).siblings('.help-wrapper').fadeToggle(300);

Upvotes: 2

Sudharsan S
Sudharsan S

Reputation: 15393

Use next or siblings in the context

$('.help').on('click', function () {
  $(this).next('.help-wrapper').fadeToggle(300);
});

or

 $('.help').on('click', function () {
  $(this).siblings('.help-wrapper').fadeToggle(300);
});

Upvotes: 4

Related Questions