【发布时间】:2019-04-03 00:30:30
【问题描述】:
我有一个父节点 div 包含几个 span 元素一起形成一个句子或段落。例如,
<div>
<span class="red">I </span>
<span class="normal">love </span>
<span class="red">you</span>
<span class="normal">.</span>
</div>
我想使用 JavaScript 在div 的第一个子节点中的“I”之后插入一个值为“don't”的span 节点,如下所示
// Note that the position is between the text, not the node positions
// No JavaScript function exists like the below, btw
document.getElementsByTagName("div")[0].insertNodeAtPos(2, mySpanElement);
为此,我有一个数字位置(此处为 2),这样第一个节点将是:
<span class="red">I <span>don't</span>
如果我有位置 3,那么第一个子节点将保持不变,第二个子节点将是:
<span class="normal"><span>don't</span>love </span>
那么,无论div 中的子节点如何,如何在任意位置插入节点?插入的节点也可以在子节点内。我需要在没有任何框架的 vanilla JavaScript 中执行此操作。
提前致谢。
【问题讨论】:
-
是不是就在
I之后 -
@Bibberty 不,它在那些 元素的文本值中的任何位置偏移之后。我以 2 作为该位置的示例,这将导致 span 在“I”之后插入。
-
好的,但偏移量与我注意到的单词相反。我想我明白了。
标签: javascript html