javascript - 查找具有已知 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 选择器给出):
/h1[1]
/p[1]/b[1]
/p[1]/span[1]
解决方案
您可以使用 javascript 循环遍历elements
DOM 中的所有内容并检查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
,700
或900
.
一旦您确定了一个粗体字,您就可以对其element
应用一个标识。class
element
工作示例:
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>
推荐阅读
- c# - 通过 VSTS REST 客户端 API 下载多个 git 项内容的有效方法
- php - 检查一个集合是否包含另一个集合?
- bash - Unix 排序不是从第一个字符开始
- eclipse-cdt - Eclipse CDT:是否可以在没有输出的 Eclipse IDE 中定义工具?
- vba - 代码仅在单步执行代码时运行 - 竞争条件?
- php - PHP 注册表单不起作用 - 现已修复
- python - 在 Python 中读取 NFC
- angular - 如何在文档中下载角度材料?
- php - 为什么当我从数据库中删除图像时也没有从服务器文件夹中删除?
- linux - 使用 '&' 运行的带有 2 个函数的循环仍然连续运行它们