示例:
<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
。如何选择我想要的部分。
答案 0 :(得分:2)
这个简单的技巧有助于获得你想要的东西。
$('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
答案 1 :(得分:1)
相反,使用.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();