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   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>
1
</td>
</tr>
<tr>
<td>
2
</td>
</tr>
</table>
</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 within element should not be taken into picture and only the at the end (right after table ends) is what I wish to remove. Could anyone think of a solution to solve this problem?
Thanks
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>
1
</td>
</tr>
<tr>
<td>
2
</td>
</tr>
</table>
table
</div>