Search code examples
jquerydom-traversal

jQuery - Finding nearest match using a generic function


I have an interface that can toggle the displaying of help by clicking a caret icon. Previously, I selected and toggled using hard-coded IDs; now, instead, I'm trying to write a generic function to handle everything. Here's an example of my DOM:

<h3 class="box-header">Step 1</h3>
<i class="fa fa-caret-down help-toggle" data-toggle="tooltip" title="Click for help"></i>
<div class="box-body">
    <div class="row">
        <div class="col-md-12">
            <p class="help-text" style="display:none;">This is help for Step 1</p>
        </div>
    </div>
</div>

<h3 class="box-header">Step 2</h3>
<i class="fa fa-caret-down help-toggle" data-toggle="tooltip" title="Click for help"></i>
<div class="box-body">
    <div class="row">
        <div class="col-md-12">
            <p class="help-text" style="display:none;">This is help for Step 2</p>
        </div>
    </div>
</div>

The jQuery function I've written partially works, in that it finds the help-text and toggles its display; however, it is toggling ALL help-texts in unison. I want it to only toggle the closest help-text. Here is the function:

$('.help-toggle').click(function () {
    $(this).toggleClass('fa-caret-up fa-caret-down');
    $(this).closest('.row').find('.help-text').slideToggle("fast");
});

I've done some searching around and found this helpful article but I'm still missing something. Any ideas? Thanks in advance!


Solution

  • Change:

    $(this).closest('.row').find('.help-text').slideToggle("fast");
    

    to:

    $(this).next('div.box-body').find('.help-text').slideToggle("fast");
    

    .closest() searches up the DOM, and you wanted the node after the help-toggle element.

    jsFiddle example