例使用cheerio文本區域:如何選擇在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
。我如何選擇我想要的部分。
例使用cheerio文本區域:如何選擇在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
。我如何選擇我想要的部分。
相反,使用.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();
這種簡單的技巧將有助於得到你想要的。
$('div.A')
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
其基於克隆方法,您可以閱讀更多關於它from here。
$('div.A').clone().children().remove().end().text() //single line representation