Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery getting the closest div with a class

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

like image 704
kritya Avatar asked Aug 01 '11 06:08

kritya


2 Answers

.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.

like image 73
Salman A Avatar answered Nov 06 '22 04:11

Salman A


$(this).nextAll(".showchars:first").html("hmm");
like image 1
Igor Dymov Avatar answered Nov 06 '22 03:11

Igor Dymov