[英]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.