简体   繁体   中英

add another class on several div

I'm trying to add another class on my divs by using javascript but it's not working. I have to call the class "olds" because I've several similar tables with div "mydiv" I don't want to change

here is the JS


$(".olds").next(tr).next(td).find(.mydiv).addclass("plop");

here is the HTML

<table>
  <tr><th><span class="olds">blaa</span></th></tr>
  <tr><td>
    <div class="mydiv"></div>
    <div class="mydiv"></div>
    <div class="mydiv"></div>
    <div class="mydiv"></div>
  </td></tr>
</table>

and here is what I want by using "addclass"

<table>
  <tr><th><span class="olds">blaa</span></th></tr>
  <tr><td>
    <div class="mydiv plop"></div>
    <div class="mydiv plop"></div>
    <div class="mydiv plop"></div>
    <div class="mydiv plop"></div>
  </td></tr>
</table>

You have a small error. It's addClass and not addclass . You also need to enclose the element names in quotation marks.

https://api.jquery.com/addclass/

One solution is to traverse up the DOM by finding the closest table and then traversing down with the find method.

 $(".olds").closest("table").find(".mydiv").addClass("plop"); 
 .plop { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><th><span class="olds">blaa</span></th></tr> <tr><td> <div class="mydiv">Div 1</div> <div class="mydiv">Div 2</div> <div class="mydiv">Div 3</div> <div class="mydiv">Div 4</div> </td></tr> </table> 

Your JS won't be able to find some of the objects as they will be null. Try this one

$(".olds").next("tr").next("td").find(".fofo").addClass("plop");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM