gpt4 book ai didi

javascript - 用混合内容的 HTML 字符串替换 textNode

转载 作者:行者123 更新时间:2023-11-28 00:41:30 25 4
gpt4 key购买 nike

对于这个 HTML 节点:

<div><i>foo</i> and <i>bar</i> go ### with <b>baz</b></div>

我想替换字符串 ###与另一个节点( <u>well</u> ),而不替换整个 innerHTML wrapper div .

预期结果:

<div><i>foo</i> and <i>bar</i> go <u>well</u> with <b>baz</b></div>

我的方法是迭代childNodes,只过滤TEXT_NODE带有我想用 replaceChild 替换和替换那些文本节点的字符串的元素使用 DOM 片段来保存替换的内容:

var root = document.querySelector('div'),
tag = "<u>well</u>",
tempFrag = document.createDocumentFragment(),
children = root.childNodes,
replacedString;

for( var i = children.length; i--; ){
if( children[i].nodeType === Node.TEXT_NODE &&
children[i].nodeValue.length > 1 &&
children[i].nodeValue.indexOf('###') != -1 ){

replacedString = children[i].nodeValue.replace('###', tag);

console.log( replacedString );
tempFrag.innerHTML = replacedString;
children[i].parentNode.replaceChild(tempFrag, children[i])
}
}
<div><i>foo</i> and <i>bar</i> go ### with <b>baz</b></div>


如您所见,替换 textNode以这种方式无法按预期工作。

虽然我可以手动提取 replacedString 的每个部分并将其分解为:

`before textNode` / New element / `after textNode` 

然后将它们全部拼凑起来,这将创建大量代码(这实际上是我目前正在做的方式,并且我试图想出一种更聪明的方法,但该片段对解析 &如你所见插入)

最佳答案

取而代之的是:

replacedString = inputChildren[i].nodeValue.replace('###', tag);

你可以使用

var offset = ...indexOf('###');
replacementNode = textnode.splitText(offset);

然后通过添加

textnode.parent.insertBefore(wrapper, replacementNode);

你可以实现你想要的。

关于javascript - 用混合内容的 HTML 字符串替换 textNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com