我有一个父div
节点包含几个span
元素一起形成一个句子或段落。例如,
<div>
<span class="red">I </span>
<span class="normal">love </span>
<span class="red">you</span>
<span class="normal">.</span>
</div>
我想在span
的第一个子节点中使用JavaScript在“I”之后插入一个值为“do not”的div
节点,就像这样
// 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中执行此操作。
提前致谢。
你可以使用insertBefore。
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
insertedNode
正在插入的节点,即newNode
parentNode
新插入节点的父节点。newNode
要插入的节点。referenceNode
插入newNode
之前的节点。这里,它使用零基索引。尝试更改值。
// Assumes every word has a span wrapper.
function insertAtNodePosition(pos, element) {
// get container node
let container = document.querySelector('div');
// array of the words (span)
let words = container.querySelectorAll('span');
// determine which one to add before
let word = words[pos];
if(word) {
container.insertBefore(element, word);
} else {
container.childNodes.appendChild(word);
}
}
let myElement = document.createElement('span');
myElement.innerText = "don't ";
insertAtNodePosition(0, myElement);
<div>
<span class="red">I </span>
<span class="normal">love </span>
<span class="red">you</span>
<span class="normal">.</span>
</div>
<!--
I want to insert a span node with value of "don't" after "I " in the first child node in the div using JavaScript, like this
// 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);
-->