首页 > 解决方案 > 将节点插入到文本中各种其他节点之间的特定位置

问题描述

我有一个父div节点,其中包含几个span元素一起形成一个句子或段落。例如,

<div>
  <span class="red">I </span>
  <span class="normal">love </span>
  <span class="red">you</span>
  <span class="normal">.</span>
</div>

我想在使用 JavaScriptspan的第一个子节点中的“I”之后插入一个值为“don't”的节点,如下所示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 中执行此操作。

提前致谢。

标签: javascripthtml

解决方案


在这里,这使用基于零的索引。尝试更改值。

// 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);
-->


推荐阅读