如何删除 div 中的单个文本节点而不删除所有文本节点?
如何删除单个动态创建的文本节点?
我正在动态生成输入,并使用 .createTextNode 在元素之前放置描述性文本。我需要能够删除正在创建的特定元素,并使用 .removeChild 来执行此操作。这对于删除单个输入效果很好,因为我有一些要引用的内容(id/name)。有没有办法为每个文本节点设置某种引用,以便我可以将其及其相应的输入控件删除?
var box = document.getElementById("myDiv");
box.appendChild(document.createTextNode('Status: '));
var inp = document.createElement('input');
inp.type = 'text';
// add attributes, etc...
box.appendChild(inp);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不首先将两者都包装在字段集中呢?
这样,只需删除字段元素就会同时删除您的文本节点和输入。
Why not wrap both in a fieldset to begin with?
This way just removing the field element will remove both your textnode and your input at the same time.
保留对它的引用:
然后删除:
如果节点应该紧接在输入之前,这也将起作用:
如果您不使用
innerHTML
或normalize( ,它应该起作用)
,这可能会导致节点被重新创建或合并,从而使您的引用无效。如果您想从节点中删除任意文本,可以使用
textnode.splitText(offset)
。Keep reference to it:
and then remove with:
If node is supposed to be immediately before the input, this will work as well:
It should work if you don't use
innerHTML
ornormalize()
, 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)
.不要删除属于 DOM 中文本节点列表一部分的文本节点。即使您引用它们(在将它们附加到 DOM 之前)。
浏览器可能会合并多个文本节点!我不确定标准的规定是什么,但它是可能的 - 至少一些经验告诉我..(可能是旧浏览器,但情况确实如此)。
相反,您可以将每个文本节点包装在 span 或 div 标记中,或者可以使用某种文本替换。我更喜欢前者。
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.
如果你把这一行:改为
:
那么你可以稍后引用textNode var来删除它。但要小心,一些浏览器会合并相邻的文本节点。
If you change this line:
To:
Then you can refer to the textNode var later to delete it. Be careful, though--some browsers will merge adjacent text nodes.