Search code examples
jqueryparents

Gotta catch anteriors elements with parents


My html:

<dl class="last">
    <dt><label>Medidas</label></dt>
    <dd class="last">
        <div class="input-box">
            <input type="text" value="" name="options[22]" class="input-text  product-custom-option" id="options_22_text" onchange="opConfig.reloadPrice()">
        </div>
    </dd>
</dl>

I have the id options_22_text as reference, I need to add a class on the dl.

Can someone help me?

I wish the result was that:

<dl class="last myClass">
    <dt><label>Medidas</label></dt>
    <dd class="last">
        <div class="input-box">
            <input type="text" value="" name="options[22]" class="input-text  product-custom-option" id="options_22_text" onchange="opConfig.reloadPrice()">
        </div>
    </dd>
</dl>

Solution

  • You can use .closest():

    For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

    $('#options_22_text').closest('dl').addClass('myClass');