2016-11-21 62 views
0

我只想访问h1的文本(在这种情况下为H1 title is here),但它会打印所有内容。我试图在text()之前加.remove('.small-title'),但它不起作用。使用Cheerio访问包含其他元素的类的文本

<div class="modal-know> 
    <h1> 
    H1 title is here 
    <div class="small-title"> 
    <a href="title-a">Click</a> 
    <a href="title-b">Click 2</a> 
    </div> 
    </h1> 
</div> 

Node.js的代码

var newsTitle = $2('.modal-know h1').text(); // prints out everything 
console.log(newsTitle); 

回答

0

看看cheerio docs: text()

它说

,包括他们的后代

这是相同的行为的jQuery的.text()

因此,也许这个答案可以帮助你:jQuery: using .text() to retrieve only text not nested in child tags

这里有我测试的代码:

let newsTitle = $('.modal-know h1').contents()[0].nodeValue; 
// solution 2: 
// .clone() //clone the element 
// .children() //select all the children 
// .remove() //remove all the children 
// .end() //again go back to selected element 
// .text(); // prints out everything 

//solution 3: 
// .contents().filter(function(){ 
//  return this.nodeType == 3; 
// })[0].nodeValue; 
console.log(newsTitle); 

*你的代码示例疗法是缺少的“在div模式 - 知道类

<div class="modal-know> -> <div class="modal-know"> 
相关问题