我正在段落/div 元素中搜索 ^ 的特定字符,希望替换新创建的 SPAN 元素中的以下内容并将其上升(制作索引)。除了我附加 SPAN 元素的位置之外,一切都成功。我希望将其附加到我找到所述字符的位置,但是,除了找到该字符的索引之外,我没有任何线索可以找到该位置。
我知道可以使用 insertAfter() 但在这种情况下不起作用,因为我试图将元素附加到段落/div 内的某个字符之后而不是某个元素之后。
<div class="codeBlock">
<span style="font-weight: normal; font-size: 20px;">Product Rule</span><br><br><br>
f(x) = u * v<br>
f'(x) = u'v + v'u<br>
<br>
<br>
<span style="font-weight: bold; font-size: 20px">I.E.</span> // Check<br><br>
f(x) = x^3 + 9
</div>
function quill() {
var blocks = document.getElementsByClassName("codeBlock");
for (block of blocks) {
for (let i = 0; i < block.textContent.length; i++) {
var ch = block.textContent[i];
if (ch == "^") {
// Loop until space
var l = i+1;
var superscript = document.createElement("SPAN");
var indice = "";
do {
indice += block.textContent[l];
l++;
} while (block.textContent[l] != " ");
superscript.textContent = indice;
superscript.className = "superscript";
block.appendChild(superscript);
console.log(indice);
}
}
}
}
quill();
当我追加元素时,html 看起来像这样:
<p>
f(x) = x^2 /*Found the character*/ + 6
<span>2</span> /*So it appends the element at the end*/
</p>
当我试图得到这样的东西时:
<p>
f(x) = x^2 /*Oh! Found the character and position,
append element here in between x^2 and + 6*/<span>2</span> + 6
</p>
最佳答案
我想你应该使用正则表达式
function quill() {
var blocks = document.getElementsByClassName("codeBlock");
for (block of blocks) {
block.innerHTML = block.innerHTML.replace(/(\^\d+)/, function(item){return '<sup>'+item+'</sup>';});
}
}
quill();
关于javascript - 在父级 HTML 字符串之间的特定点附加 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56291000/