【问题标题】:how to loop through nested 'div' elements using cheerio如何使用cheerio遍历嵌套的'div'元素
【发布时间】:2020-12-14 09:50:21
【问题描述】:

我正在尝试修改我的 HTML 中的每个 <div> 元素,方法是使用cheerio 用新行换行。

输入:

<html>
    <body> 
        <div>
            <div><div>Hi</div></div>
            <div>hello</div>
            <div>ur awesome</div>
        </div>
    </body>
</html>

预期输出:

<html>
    <body> 

        <div>

            <div>

                <div>Hi</div>

            </div>


            <div>hello</div>


            <div>ur awesome</div>

        </div>

    </body>
</html>

我得到的输出:

<html><head></head><body> 
        
 <div>
            <div><div>Hi</div></div>
            <div>hello</div>
            <div>ur awesome</div>
        </div> 

    
</body></html>

问题:它没有向嵌套的&lt;div&gt; 元素添加新行。尝试使用 $(this) 上下文但没有用。

代码

const c = require('cheerio')
const $ = c.load(html);

$('div').each((i,e) => {
    let mod = `\n ${ c.html($(e)) } \n`
    $(e).replaceWith(mod)
})

console.log($.html())

【问题讨论】:

    标签: javascript jquery node.js cheerio


    【解决方案1】:

    你可以这样做:

    $('div').before("\n").after("\n")
    

    【讨论】:

    • 谢谢,这行得通。我不知道我们可以在不循环的情况下做到这一点:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2011-03-02
    • 1970-01-01
    • 2019-08-19
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多