首页 > 解决方案 > 查找具有已知 CSS 属性的 HTML 片段

问题描述

我正在寻找某种“反向 CSS 选择器”:给定一个 HTML 文档,如何查找具有特定格式的片段?例如,我想获取使用粗体文本 ( font-weight: bold;) 的段列表。鉴于此文件:

<h1>example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>

然后段列表将包括(例如通过 XPath 选择器给出):

标签: javascriptcsscss-selectorsgetcomputedstyle

解决方案


您可以使用 javascript 循环遍历elementsDOM 中的所有内容并检查font-weight每个内容element

window.getComputedStyle(myDOMElement).getPropertyValue('font-weight');

一个 font-weight400是正常的(在 CSS 中,font-weight: normal并且font-weight: 400是相同的),所以font-weight上面的任何一个都400意味着该元素是粗体的。

注意在 CSS 中,afont-weight通常是400,700900.

一旦您确定了一个粗体字,您就可以对其element应用一个标识。classelement

工作示例:

const allDOMElements = document.querySelectorAll('*');

for (let i = 0; i < allDOMElements.length; i++) {

  let fontWeight = window.getComputedStyle(allDOMElements[i]).getPropertyValue('font-weight');

  if (fontWeight > 400) {

    allDOMElements[i].classList.add('is-bold');
  }
}
.is-bold {
  color: rgb(255, 0, 0);
}
<h1>Example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>


推荐阅读