简体   繁体   English

如何在JavaScript中使用Cheerio选择文本区域

[英]How do I select the text area using cheerio in javascript

Example: 例:

<div class="A">
    I'm in A.
    <h1 class="B">
           I'm in A and B.          
    </h1>
    I'm in A, too.
</div>

If I use $('div.A').text() to select, I will also get I'm in A and B . 如果我使用$('div.A').text()进行选择,我也将I'm in A and B But I just want to get I'm in A and I'm in A, too . 但是我只想让I'm in AI'm in A, too How do I select the part I want. 如何选择想要的零件。

This simple trick would help get what you want. 这个简单的技巧将帮助您获得所需的东西。

$('div.A')
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

Its based on the clone method, you can read more about it from here . 它基于克隆方法,您可以从此处阅读有关它的更多信息。

$('div.A').clone().children().remove().end().text() //single line representation

Instead, of using .text , use .contents to get all of the nodes (including text nodes), then use each to loop through them and only get the text of the text nodes: 相反,不使用.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."]

(Actual logged contents will likely have whitespace around them as that whitespace is in the text node, depending on the exact markup.) (实际记录的内容可能会在其周围带有空格,因为该空格位于文本节点中,具体取决于确切的标记。)

Or if you prefer: 或者,如果您愿意:

var text = $("div.A")
    .contents()
    .filter(function() {
        return this.nodeType === 3; // 3 = Text node
    })
    .map(function() {
        return this.nodeValue;
    })
    .get();

Which looks a lot tidier in ES2015+: 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM