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

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

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