[英]How do I select the text area using cheerio in javascript
例:
<div class="A">
I'm in A.
<h1 class="B">
I'm in A and B.
</h1>
I'm in A, too.
</div>
如果我使用$('div.A').text()
进行选择,我也将I'm in A and B
但是我只想让I'm in A
, I'm in A, too
如何选择想要的零件。
这个简单的技巧将帮助您获得所需的东西。
$('div.A')
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
它基于克隆方法,您可以从此处阅读有关它的更多信息。
$('div.A').clone().children().remove().end().text() //single line representation
相反,不使用.text
,而是使用.contents
获取所有节点(包括文本节点),然后使用each
节点遍历它们,仅获取文本节点的文本:
var text = [];
$("div.A").contents().each(function() {
if (this.nodeType === 3) { // 3 = Text node
text.push(this.nodeValue);
}
});
console.log(text); // ["I'm in A.", "I'm in A, too."]
(实际记录的内容可能会在其周围带有空格,因为该空格位于文本节点中,具体取决于确切的标记。)
或者,如果您愿意:
var text = $("div.A")
.contents()
.filter(function() {
return this.nodeType === 3; // 3 = Text node
})
.map(function() {
return this.nodeValue;
})
.get();
在ES2015 +中看起来更整洁:
let text = $("div.A")
.contents()
.filter((i, e) => e.nodeType === 3)
.map((i, e) => e.nodeValue)
.get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.