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

324
Visualizações
How can I remove html elements that are nested into each other?

I have an html structure like this:

<p>Hello</p>
<h1>ah</h1>
<child>
    <p>Haha</p>
    <child>
      <p>Hihi</P>
    </child>
</child>
<child>
<h4>Hello</h4>
</child>
<h3>Hello</h3>

Goal:

My Goal is to remove all child tags from the DOM to receive this:

<p>Hello</p>
<h1>ah</h1>
<h3>Hello</h3>

What I tried:

const html = document.createElement('div');
//This is the HTML I pasted above.
html.innerHTML = this.item.Body;
let childTags = html.getElementsByTagName('child');

for (let i = 0; i < childTags.length; i++) {
  let childTag = childTags[i];
  childTag.remove();
}

this.item.Body = html.innerHTML;

My Problem:

The problem that I am having is that getElementsByTagName finds the nested tag that is already removed when I remove the parent child tag, this makes it so the for loop doesn't work.

Any help appreciated.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I solved it myself, and it was embarassingly easy.

I had to make a recursive function.

removeChildComponents() {
const html = document.createElement('div');
html.innerHTML = this.item.Body;

let childTag = html.getElementsByTagName('child');
if (childTag.length > 0) {
        childTag[0].remove();
}

this.item.Body = html.innerHTML;

const recursionHandler = html.getElementsByTagName('child')
if (recursionHandler.length > 0) {
        this.removeChildComponents();
};
};

about 4 years ago · Juan Pablo Isaza Relatório

0

Here you go. Firstly you getElementsByTagName that returns an HTMLCollection which you convert into an array using Array.prototype.slice. Then forEach child i.e item in array, you .remove() it from DOM.

Array.prototype.slice.call(document.getElementsByTagName('child')).forEach(child => child.remove());
<p>Hello</p>
<h1>ah</h1>
<child>
  <p>Haha</p>
  <child>
    <p>Hihi</p>
  </child>
</child>
<child>
  <h4>Hello</h4>
</child>
<h3>Hello</h3>

about 4 years ago · Juan Pablo Isaza 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