【发布时间】:2021-02-16 10:06:34
【问题描述】:
我有以下 HTML 已传递到 Cheerio:
<h1 id="heading1">heading1</h1>
<p>text</p>
$.root().html() 的输出是这样的:
<html><head></head><body><h1 id="heading1">heading1</h1>
<p>text</p>
</body></html>
我需要遍历 body 的子节点并在每个非 h1 子节点上调用 .html() ,并对每个 h1 子节点执行其他操作。
按顺序循环遍历元素很重要,我不能同时选择 body 和 .html() 的所有非 h1 子级。
我试过了:
var children = $("body").first().children();
for(var i = 0; i < children.length; i++){
console.log(children[i].html()); // children[i].html() is not a function
}
但是从数组中选择一个孩子后我不能调用 .html() 。 .html() 在使用 children.each 时也不是一个函数。
.html() 是一个函数,如果不是使用 [i] 从数组中获取元素,而是使用 .first(),但显然这只适用于第一个元素。
【问题讨论】:
标签: javascript cheerio