JQuery gets the closest div with class

Hii I want to show numeric characters for the closest div with the showchars class.

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 on input fields, it dumps the contents of the error class.

But does not change the text to: hmm in the div.

Where am I mistaken or the best way to get the closest div and then implement api: .html("hmm") ?

thanks

+6
source share
2 answers

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

In your example .showchars is the parent of the text field, so instead of .siblings() .

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

Demo is here .

+6
source
 $(this).nextAll(".showchars:first").html("hmm"); 
+1
source

Source: https://habr.com/ru/post/894011/


All Articles