How to remove an individual text node in a div without removing all of them?

32.8k Views Asked by At

How do I go about removing an individual dynamically created text node?

I am generating input's on the fly and am using .createTextNode to place descriptive text before the elements. I need the ability to delete specific elements that are being created and am using .removeChild to do it. That works fine for removing an individual input because I have something to reference (id/name). Is there a way to set some sort of reference to each text node so I can delete it along with its corresponding input control?

var box = document.getElementById("myDiv");

box.appendChild(document.createTextNode('Status: '));
var inp = document.createElement('input');
inp.type = 'text';
// add attributes, etc...

box.appendChild(inp);
5

There are 5 best solutions below

2
On BEST ANSWER

Why not wrap both in a fieldset to begin with?

var box = document.getElementById("myDiv");

var field = document.createElement('fieldset');
field.appendChild(document.createTextNode('Status: '));
var inp = document.createElement('input');
inp.type = 'text';
// add attributes, etc...

field.appendChild(inp);
box.appendChild(field);

This way just removing the field element will remove both your textnode and your input at the same time.

0
On

If you change this line:

box.appendChild(document.createTextNode('Status: '));

To:

var textNode = document.createTextNode('Status: ');
box.appendChild(textNode);

Then you can refer to the textNode var later to delete it. Be careful, though--some browsers will merge adjacent text nodes.

0
On
var box = document.getElementById("myDiv");

var label = document.createTextNode('Status: ')
box.appendChild(label);
var inp = document.createElement('input');
inp.type = 'text';
// add attributes, etc...

box.appendChild(inp);

// do other stuff

//remove the label
label.nodeValue = "";
0
On

Do not remove text nodes that are part of a list of textnodes in the DOM. Even if you reference them (before you appended them to the DOM).

The browser may merge multiple text nodes! I am not sure what the standards state, but its possible - at least some experience told me.. (may be old browsers, but it was the case).

Instead of that, you could either wrap each text node in a span or div tag, or you could use some kind of text replacements. I'd prefer the former.

0
On

Keep reference to it:

var txt = document.createTextNode('Status: ');
box.appendChild(txt);

and then remove with:

txt.parentNode.removeChild(txt);

If node is supposed to be immediately before the input, this will work as well:

inp.parentNode.removeChild(inp.previousSibling);

It should work if you don't use innerHTML or normalize(), which could cause nodes to be re-created or merged, invalidating your references.

In case you wanted to remove arbitrary text from a node, there's textnode.splitText(offset).