首页 > 解决方案 > 如果元素为空,则使用 JS 删除 css 类

问题描述

我有多个表格在整个文档中保存图像。每个表有 3 行(标题/图像/来源)。我需要使用 CSS 为我的标题设置边框,但是当标题为空白时,标题类仍然出现在我的标记中,导致出现随机边框。

带标题的表格:

<table class="img-include">
  <tr>
    <td class="caption">My Caption </td>
  </tr>
  <tr>
    <td class="image"><img src="..." /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>

没有标题的表格,class="caption" 仍在表格单元格中:

<table class="img-include">
  <tr>
    <td class="caption"></td>
  </tr>
  <tr>
    <td class="img"><img src="..." /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>

我想删除空单元格的标题类,但我当前的 JS 删除了我所有元素的类:

//remove empty caption
if ($('.caption').is(':empty')){
  $("td").removeClass( ".caption" );
}

我该如何更新它,以便它只删除空 .caption 单元格的类

JS 小提琴:https ://jsfiddle.net/5dq63zL4/

标签: javascriptjqueryhtmlcss

解决方案


很容易

td.caption:empty{
  border:none
}

推荐阅读