将节点插入到各种其他节点之间的文本中的特定位置

问题描述 投票:1回答:2

我有一个父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中执行此操作。

提前致谢。

javascript html
2个回答
0
投票

你可以使用insertBefore

var insertedNode = parentNode.insertBefore(newNode, referenceNode);
  • insertedNode正在插入的节点,即newNode
  • parentNode新插入节点的父节点。
  • newNode要插入的节点。
  • referenceNode插入newNode之前的节点。

0
投票

这里,它使用零基索引。尝试更改值。

// 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);
-->
© www.soinside.com 2019 - 2024. All rights reserved.