简体   繁体   English

在几个div上添加另一个类

[英]add another class on several div

I'm trying to add another class on my divs by using javascript but it's not working. 我正在尝试使用javascript在div上添加另一个类,但是它不起作用。 I have to call the class "olds" because I've several similar tables with div "mydiv" I don't want to change 我必须将类称为“ olds”,因为我有几个与div类似的表“ mydiv”,我不想更改

here is the JS 这是JS


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

here is the HTML 这是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" 这是我想要通过使用“ 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 . 它是addClass而不是addclass You also need to enclose the element names in quotation marks. 您还需要将元素名称括在引号中。

https://api.jquery.com/addclass/ 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. 一种解决方案是通过查找最接近的表来遍历DOM,然后使用find方法来遍历DOM。

 $(".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. 您的JS无法找到某些对象,因为它们将为null。 Try this one 试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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