I am parsing articles that can occasionally have duplicated formatting tags, resulting in bloated HTML, and preventing proper conversion into e.g. Markdown.
Example:
<p>
This is an article
<strong>with <a href="#"><b>nested</b></a> <strong>emphasized words</strong></strong>
</p>
The result should, thus, be:
<p>
This is an article
<strong>with <a href="#">nested</a> emphasized words</strong>
</p>
(for sake of my cleanup, I treat bold and strong equally, even if they are semantically different)
My intuition was to set up an array with the duplicates
const duplicates = [
["strong", "b"],
["em", "i"],
];
And then finding all elements that are in the list using
let searchTags: string[] = [];
searchTags.concat(...duplicates);
// Search for all formatting tags
const result: NodeList = doc.querySelectorAll(searchTags);
// ... in each result, check for formatting type, and check for children of the same formatting type
However, this looks like a wildly inefficient way to traverse the DOM, and I'd have to run the querySelectorAll to update the NodeList after every iteration to ensure already removed nodes are not being traversed.
It seems there should be an easier way to identify descendants (even if they are deeply nested and not direct child nodes) of the same tag, and remove the tag, but I cannot fathom it.
Thanks :-)
const duplicates = [
["strong", "strong"],
["strong", "b"],
["em", "i"],
];
for(let i =0; i<duplicates.length; i++){
let sel = [duplicates[i].join` `,duplicates[i].reverse().join` `].join`,`;
document.querySelectorAll(sel)
.forEach(tag=>tag.replaceWith(document.createTextNode(tag.innerText)));
}
console.log(document.querySelector('p').outerHTML);
<p>
This is an article
<strong>with <a href="#"><b>nested</b></a> <strong>emphasized words</strong></strong>
</p>