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

339
Vistas
Removing &nbsp element from a div element

I am trying to work on a logic which removes   elements if it exist within a div element. I tried the logic of replacing the   element as follows:

(div.html().replace(/^\s* /m, ''));

But the problem with the scenario I am trying to handle is, I would want to remove the &nbsp elements which are existing only at the immediate children level of an element, that is suppose we have the following html content:

<div class="block">
  <table>
    <tr>
      <td>
       &nbsp; 1 
      </td>
    </tr>
    <tr>
      <td>
        2
      </td>
    </tr>
  </table>
  &nbsp;
</div>

Consider the div element with class name block as the parent element we are taking. Here I would like to look at only the children of this element and not within those child elements which means that the &nbsp; within element should not be taken into picture and only the &nbsp; at the end (right after table ends) is what I wish to remove. Could anyone think of a solution to solve this problem?

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Test each child node of the div and remove the node where the nodeName is '#text', and the result of checking the nodeValue for the character code is true.

const div = document.querySelector('.block');
const regex = /(\u00a0).+/;

function remove(div) {
  const nodes = div.childNodes;
  console.log(`Current nodes: ${nodes.length}`);
  nodes.forEach(node => {
    if (node.nodeName === '#text') {
      if (regex.test(node.nodeValue)) {
        div.removeChild(node);
      }
    }
  });
  console.log(`Remaining nodes: ${nodes.length}`);
}

remove(div);
<div class="block">
  <table>
    <tr>
      <td>
       &nbsp; 1 
      </td>
    </tr>
    <tr>
      <td>
        2
      </td>
    </tr>
  </table>
  &nbsp;
  &nbsp;table
</div>

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