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

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

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