jQuery getting the closest div with a class

2019-04-07 19:58发布

问题:

Hii i want to show the number chars to the closest div with the class showchars.

I tried to do this :

$('#maina').focus(function() {
$(this).closest("div.showchars").find(".countchars").html("KKK");
    $("#error-1").html("");
    $(this).closest(".showchars").html("hmm");
});

With this html:

    <tr>
    <td>
    Main Alliase/Current Alliase:
    </td>
    <td><input type="text" id="maina" class="countchars"/><br />
    <div class="showchars">o</div>
    </td>
<td><span id="handle-1" class="selector">?</span></td>
    <td><div id="error-1" class="errors"></div></td>
    </tr>

When i focus into the input boxes it does resets the content of the errors class.

But doesnt changes text to : hmm in the div.

Where have been i going wrong or what is the better way to get the closest div and then implement the api : .html("hmm") ?

Thanks

回答1:

.closest() looks at the element itself and its parents for a match.

In your example, .showchars is a sibling of the textbox so you could use .siblings() instead.

$(this).siblings(".showchars").html("hmm");

Demo here.



回答2:

$(this).nextAll(".showchars:first").html("hmm");