Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用混合内容HTML字符串替换textNode 对于此HTML节点:_Javascript_Html_Dom - Fatal编程技术网

Javascript 用混合内容HTML字符串替换textNode 对于此HTML节点:

Javascript 用混合内容HTML字符串替换textNode 对于此HTML节点:,javascript,html,dom,Javascript,Html,Dom,我的方法是迭代childNodes,仅使用我要替换的字符串过滤TEXT\u NODE元素,并使用DOM片段保存替换的内容,将这些textNodes替换为replaceChild: var root=document.querySelector('div'), tag=“well”, tempFrag=document.createDocumentFragment(), children=root.childNodes, 替换字符串; for(var i=childrence.length;i-

我的方法是迭代childNodes,仅使用我要替换的字符串过滤
TEXT\u NODE
元素,并使用DOM片段保存替换的内容,将这些textNodes替换为
replaceChild

var root=document.querySelector('div'),
tag=“well”,
tempFrag=document.createDocumentFragment(),
children=root.childNodes,
替换字符串;
for(var i=childrence.length;i--;){
if(children[i].nodeType===Node.TEXT\u 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])
}    
}
foo和bar go#####与baz
代替此:

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

var offset = ...indexOf('###');
replacementNode = textnode.splitText(offset); 
然后加入

textnode.parent.insertBefore(wrapper, replacementNode);
你可以实现你想要的。

var root=document.querySelector('div'),
tag=document.createElement('u'),
children=root.childNodes,
替换节点,
idx;
tag.innerHTML=“well”;
for(var i=childrence.length;i--;){
if(children[i].nodeType===Node.TEXT\u Node&&
children[i].nodeValue.length>1){
idx=children[i].nodeValue.indexOf('####');
如果(idx==-1)继续;
replacedNode=children[i].splitText(idx);
//从第二个拆分文本节点(“######with”)中删除“##”
replacedNode.nodeValue=replacedNode.nodeValue.replace(“###,”);
//将tag元素放在第二个拆分的textNode之前
children[i].parentNode.insertBefore(tag,replacedNode);
}    
}

foo和bargo#####和baz
谢谢。Split很有帮助,我已经成功地制作了一个工作示例(作为答案发布),但我仍然必须替换
replacementNode
中的
\
var offset = ...indexOf('###');
replacementNode = textnode.splitText(offset); 
textnode.parent.insertBefore(wrapper, replacementNode);