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

360
Visualizações
How to remove all empty spans in <div>?

I need to remove all empty spans from one of div. The problem is, once forEach loop is done, previously not empty spans are empty now so I thought I could use while loop but it seems to loop itself. What did I do wrong?

function removeEmptySpans() {
  const tree = document.getElementById('tree')
  const spans = Array.from(tree.querySelectorAll("span"))

  let emptySpansExist = true

  while (emptySpansExist) {
    emptySpansExist = false
    spans.forEach(span => {
      if (span.innerHTML === "") {
        span.remove()
        console.log("empty span")
        emptySpansExist = true
      } else {
        console.log("not empty span")
      }
    })
  }
}
<div id="tree" onClick={removeEmptySpans}>
    <span>
        <span>
            <span></span>
        </span>
        <span>
            <span></span>
            <span><span></span><span></span></span>
            <span><span></span>content</span>
        </span>
    </span>
    <span></span>
</div>

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

0

function removeEmptySpans() {
  const tree = document.getElementById('tree');
  const spans = Array.from(tree.querySelectorAll("span")).reverse();
  for(let i=0; i<spans.length; i++) {
    if (spans[i].innerHTML.trim() === "") {
      // console.log(i, spans[i], spans[i].innerHTML, "---");
      spans[i].remove();
    }
  }
}

removeEmptySpans();

console.log('Remaining spans:', tree.querySelectorAll("span").length);
<div id="tree" onClick="removeEmptySpans()">
  <span>
                        <span>
                            <span></span>
  </span>
  <span>
                            <span></span>
  <span><span></span><span></span></span>
  <span><span></span>content</span>
  </span>
  </span>
  <span>

                    </span>
</div>

The code makes a list of all the possible spans inside the tree element.

The query selector will build a forward list but to avoid having conflicts you just need to reverse the list so you can get the empty children removed first and avoid removing a parent having different spans which some of are filled of content.

The trim method in the conditional statement allows you to remove all the empty spaces at the prefix and suffix of your innerHTML to avoid confusing the functions with spaces only.

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