【问题标题】:Insert node to a specific position in text among various other nodes将节点插入到文本中各种其他节点之间的特定位置
【发布时间】: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


【解决方案1】:

您可以使用insertBefore

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

【讨论】:

  • 我无权访问参考节点,因为我无法知道该位置位于哪个节点。如果我有一个位置 5,我怎么知道文本偏移位于哪个 节点?当然,从上面的例子中,我可以说 5 个文本偏移位于
    中的第 2 个子节点。但是我的应用程序动态添加了带有文本的子节点,因此我无法跟踪它。
  • 对,当你注意到需要在文本中插入时,我错过了。
【解决方案2】:

这里,它使用从零开始的索引。尝试更改值。

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

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签