javascript - 将节点插入到文本中各种其他节点之间的特定位置
问题描述
我有一个父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 中执行此操作。
提前致谢。
解决方案
在这里,这使用基于零的索引。尝试更改值。
// 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);
-->
推荐阅读
- node.js - 打字稿版本与节点版本
- routing - .net核心路由到基于当前域名的剃须刀页面区域?
- jira - 如何将组件添加到 Jira 项目?
- r - 向“as.matrix”显式提供 nrow 和 ncol 不会创建维度
- java - 反序列化似乎不尊重@JsonIgnore
- reactjs - 带有样式组件和 CRUD 的文件结构
- c - Called object type 'void' is not a function or function pointer
- pdf - 为什么使用 ImageMagick/Ghostscript 将此 PDF 转换为图像后缺少文本?
- python - 停止失控递归,使 Python 函数正常工作
- swift - Scanning Real-World Object and generating 3D Mesh from it