I'm using Cheerio JS to simplify some ancient HTML code and transform it into HTML5. Among other things, I'm replacing some markup-heavy quotes that look like the following:
Node to be replaced:
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
The transformed output is supposed to look like this:
<blockquote>Lorem ipsum dolor sit amet</blockquote>
Here's the code current code I'm using at this time:
$(`table[id^='post']`).each( (i, el) => {
// Get the post
let postBody = $(el).find(`div[id^='post_message_']`).html().trim();
// Replace quotes with blockquotes
cheerio.load(postBody)('div[style^="margin:20px; margin-top:5px; "]').each( (i, el) => {
if ($(el).html().trim().startsWith('<div class="smallfont" style="margin-bottom:2px">Quote')) {
let tbody = $(el).find('tbody > tr > td').html();
let quote = $(el).find('tbody > tr > td > div');
if (quote.html() && quote.text().trim().startsWith('Originally Posted by')) {
let replacement = $('<blockquote>Hello</blockquote>');
quote.parent().html().replace(quote.html(), replacement);
}
// Looks all good
console.log($(el).html())
}
postBody = $(el).html();
});
});
And lastly, more HTML for some context:
<div id="post_message_123456">
As Username has previously written
<br>
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
<br>
I think he has a point!
<img src="smile-with-sunglasses.gif" />
</div>
The replacement itself seems to work, the output of the console.log()
statement looks all good. The problem lies in the last line, where I'm trying to replace the original content with the replacement. However, postBody
looks like it did before. What am I doing wrong?
div[id^='post_message_']
element in that html