I have a React app. I also have a string that represents a div and this div contains other elements, such as input, img, div, etc. I would like to display this string as HTML using the dangerouslySetInnerHTML (which I know is very dangerous). But before I do that, I would like to remove certain elements from the string that correspond to certain tags, such as img, svg to name a few. What is the way to accomplish this?
BONUS: Each of these elements might have class, id and/or other attributes. It would be nice to remove these attributes as well.
To remove certain tags, use DOMParser to turn the string into a document, then use querySelectorAll to select all the tags you don't want and .remove() them.
To remove all attributes from all elements too, change the querySelectorAll to select all elements, and iterate over their .attributes.
const str = `
<main class="foo">
<input>
<img>
<div>div</div>
<section id="thesection" class="sectionclass">
<img>
<span>span</span>
</setion>
</main>
`;
const doc = new DOMParser().parseFromString(str, 'text/html');
const tagsToRemove = 'input, img, div';
for (const elm of doc.querySelectorAll('*')) {
if (elm.matches(tagsToRemove)) {
elm.remove();
}
for (const attrib of [...elm.attributes]) {
elm.removeAttribute(attrib.name);
}
}
console.log(doc.body.innerHTML);