You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS为含required属性input的对应th设置font-weight?或jQuery实现?

Can This Be Done with CSS?

Short answer: No, not with pure CSS right now.

Here's why: CSS selectors work in a "forward-only" direction. To target the <th> that comes before the <td> containing the required <input>, we'd need a way to:

  1. Target the <input[required]> element
  2. Jump up to its parent <td>
  3. Then select the preceding <th> sibling

Unfortunately, CSS doesn't have a parent selector (to go from child to parent), and while sibling selectors exist, they only let you target elements that come after a reference element—not before. So there's no way to write a CSS rule that reaches back to the earlier <th> based on the input inside the following <td>.

jQuery Solution

Absolutely! jQuery makes this straightforward with its traversal methods. Here's how to do it cleanly:

First, define a CSS class for the bold styling (better practice than inline styles):

.required-field-label {
  font-weight: bold;
}

Then add this jQuery code to apply the class to the correct <th> elements:

$(document).ready(function() {
  // Find all inputs with the required attribute
  $('input[required]')
    // Traverse up to their closest parent <td>
    .closest('td')
    // Select the immediately preceding <th> sibling
    .prev('th')
    // Add the bold class to that <th>
    .addClass('required-field-label');
});

How This Works:

  • $('input[required]'): Targets every <input> that has the required attribute.
  • .closest('td'): Moves up the DOM tree to find the nearest <td> parent of the input.
  • .prev('th'): Selects the sibling element immediately before that <td>—which is exactly the <th> we want to style.
  • .addClass('required-field-label'): Applies our pre-defined bold styling to that <th>.

This will automatically style the corresponding <th> for any required input on your page. If you dynamically add inputs later, you can re-run this code snippet to update the styling.

内容的提问来源于stack exchange,提问作者Jay P.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:47:06