Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda