javascript - 用cheerio检测内联元素?
问题描述
是否可以使用cheerio 检测内联元素?例如:
<div>
Hello
<strong>there</strong>
John!
</div>
这是我想检测的内联元素的示例,因为对于读者来说,strong
标签非常明显是短语其余部分的延续。但是,与这样的东西相比:
<div>
Jobs
<span>Cleaner</span>
<span>Artist</span>
</div>
这些并不完全是内联的,因为对于读者来说,它们显然是分开的。
我想我要问的是,是否可以使用cheerio 来检测元素是否夹在其父文本之间?
解决方案
注意:该术语inline elements
可能不是最好的描述您想要实现的目标。
我将采取的基本步骤是:
- 使用childNodes获取子文本和 html 元素的节点列表。
- 然后使用nodeType或类似方法来确定节点是元素还是文本。
textContent
然后检查文本元素在其各自的或数据中是否不仅包含空格字符。
使用 js,可以实现的一种方法是:
function markSandwichedEls(parent) {
var children = parent.childNodes;
for (let i = 0; i < children.length; i++) {
if (
children[i].nodeType === 1 &&
children[i - 1].nodeType === 3 &&
children[i - 1].textContent.replace(/\s/g, "").length &&
children[i + 1].nodeType === 3 &&
children[i + 1].textContent.replace(/\s/g, "").length
) {
children[i].style.backgroundColor = "red";
}
}
}
document.querySelectorAll("div").forEach(div => {
markSandwichedEls(div);
});
<div>
Hello
<strong>there</strong> John!
</div>
<div>
Jobs
<span>Cleaner</span>
<span>Artist</span>
</div>
因此,通过应用非常相似的方法,这可以在cheerio 中实现,如下所示:
const cheerio = require('cheerio')
const $ = cheerio.load(`
<div>
Hello
<strong>there</strong> John!
</div>
<div>
Jobs
<span>Cleaner</span>
<span>Artist</span>
</div>
`)
const divs = $('div')
divs.toArray().forEach(div => {
div.childNodes.forEach(child => {
if (
child.type === 'tag' &&
child.prev.type === 'text' &&
child.prev.data.trim() !== '' &&
child.next.type === 'text' &&
child.next.data.trim() !== ''
) {
console.log(child)
}
})
})
推荐阅读
- arrays - 如何在 Bash 数组中的特定元素之前搜索字符串?
- eclipse - NetSuite 的 Eclipse TWO_FA_REQD
- php - 高级自定义字段 the_sub_field()['url'] 但它不返回 URL
- java - 从eclipse启动spring-boot应用程序时出错
- python - 如何使用 django knox 对用户进行身份验证?
- amazon-cognito - 如何使用 Amplify 将图片上传到 AWS Cognito?
- python - 在 for 循环中剪辑 netcdf 文件时减少处理时间
- regex - Data Studio 中的 REGEX_EXTRACT 与正则表达式模式不匹配
- powershell - Powershell 启动进程命令未在 github 操作的分离模式下运行
- go - golang paho mqtt 丢弃消息