[英]Remove parent div class if child div has a specific value
I have the following code: 我有以下代码:
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">16</button>
</td>
Check button value if it is 16 then remove the .CalendarDay--valid
from the parent div. 检查按钮值是否为16,然后从父div中删除
.CalendarDay--valid
的.CalendarDay--valid
。
How do I do this? 我该怎么做呢?
You can use closest()
method to do that: 您可以使用
closest()
方法来做到这一点:
var elem = $('.CalendarDay__button'); if (elem.text().trim() === '16') { elem.closest('.CalendarDay--valid').removeClass('CalendarDay--valid'); }
.CalendarDay--valid button{ color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;"> <button type="button" class="CalendarDay__button">16</button> </td> </tr> </table>
Use parent
with this
for particular td
. this
特定的td
使用parent
。 I give two td
16 -- 17 on example.17 is shown but 16 remove. 我在example.17上给出了两个
td
16-17,但删除了16。
$('.CalendarDay').find('.CalendarDay__button').each(function() { if ($(this).text() == '16') $(this).parent('td').remove(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;"> <button type="button" class="CalendarDay__button">16</button> </td> <td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;"> <button type="button" class="CalendarDay__button">17</button> </td> </tr> </table>
Try this if you have multiple buttons to check: 如果您有多个按钮需要检查,请尝试以下操作:
$.each($('.CalendarDay__button'),function(){ var btn = $(this); var parent = btn.closest('.CalendarDay'); // Before console.log(parent.attr('class')) if(btn.text() == "16"){ parent.removeClass('CalendarDay--valid'); // After console.log(parent.attr('class')) } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;"> <button type="button" class="CalendarDay__button">16</button> </td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.