Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

332
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!