Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda