Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
React: Remove certain html elements from string and normalize

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.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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);

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!