html - 如何设置页面/元素中第一次出现的类的样式

标签 html css css-selectors

如何将样式 text-decoration:line-through 添加到表格中的第一个 span class="price" 元素?

我有以下 HTML 结构:

<table class="data-table" id="product-attribute-specs-table">
    <colgroup>
      <col width="25%">
      <col>
    </colgroup>
    <tbody>
      <tr class="first odd">
          <th class="label">Style Number</th>
          <td class="data last">2403</td>
      </tr>
      <tr class="even">
          <th class="label">Style Name</th>
          <td class="data last">Easy Option Berber</td>
      </tr>
      <tr class="odd">
          <th class="label">Rating</th>
          <td class="data last">3.5</td>
      </tr>
      <tr class="even">
          <th class="label">Retail Price</th>
          <td class="data last"><span class="price">$2.23</span></td>
      </tr>
      <tr class="odd">
          <th class="label">Price</th>
          <td class="data last"><span class="price">$1.44</span></td>
      </tr>
      <tr class="even">
          <th class="label">Roll Price Begins At</th>
          <td class="data last">125</td>
      </tr>
      <tr class="odd">
          <th class="label">Face Weight</th>
          <td class="data last">50</td>
      </tr>
      ...
    </tbody>
</table>

注意:我已经查看了此处的答案,但它们并不适用,因为我的类不在同一父元素中: CSS selector for first element with class

示例(不起作用):

#product-attribute-specs-table tbody > tr td.data .price {text-decoration:line-through}
#product-attribute-specs-table tbody > tr td.data .price ~ tr td.data .price {text-decoration:none}

我还应该注意 class="price" 在页面中使用了多次。我只需要定位表格内的第一个。

最佳答案

为此你需要 JS:

document.getElementById('product-attribute-specs-table')
  .querySelector('span.price')
  .classList.add('line-through');

关于html - 如何设置页面/元素中第一次出现的类的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966132/

相关文章:

javascript - 悬停事件更改为 javascript 函数

html - 页脚不会在移动 View 中停留

html - 获取CSS文件的变量?

php - 尝试从数据库 jquery 检索用户名

html - 无法为菜单选项正确放置箭头

javascript - 响应式水平滚动菜单

css - 我如何在 CSS 中将加号选择器与父类和类结合起来?

html - 正确使用CSS :not selector for excluding element when in particular container

css - 重复标题选择器

javascript - 隐藏另一个 div 之后的 div