2016-09-15 52 views
0

例使用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 AI'm in A, too。我如何选择我想要的部分。

回答

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(); 
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