I am trying to modify each <div>
element in my HTML by wrapping it with new lines using cheerio.
input:
<html>
<body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
Expected output:
<html>
<body>
<div>
<div>
<div>Hi</div>
</div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
the output I got:
<html><head></head><body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body></html>
Problem: It is not adding the new lines to the nested <div>
elements. Tried using $(this)
context but did not work.
code:
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())
You could do:
$('div').before("\n").after("\n")