jQuery克隆节点错误 [英] jQuery clone node error
问题描述
未捕获NotFoundError:无法在Node上执行appendChild:
new child元素为null。
这是我的代码:
if($(p:contains('computer forensics is'))){
var highlight = document.createElement('span');
highlight.className ='highlight';
highlight.style.backgroundColor =red;
highlight.id =;
highlight.setAttribute(title,);
var node = $(p:contains('computer forensics is'));
var wordClone = node.clone(true);
highlight.appendChild(wordClone);
node.parentNode.replaceChild(highlight,node);
}
p>
var wordClone = node.clone(true);
到这个:
var wordClone = node.clone(true)[0]; //现在是HTMLElement
您正在使用本机元素混合jQuery对象。
此外,我还没有说出你为什么要 不 在使用jQuery时可用。 / p>
您可以重写jQuery中的大部分内容:
if( $(p:contains('computer forensics is'))。length){
var highlight = $('< span />',{
class:higlight
style:background-color:red;
});
var node = $(p:contains('computer forensics is'));
var wordClone = node.clone(true);
highlight.append(wordClone);
node [0] .parentNode.replaceChild(highlight,node);
}
I have to check if a 'p' element contains some text, if so create another element 'span' then clone the 'p' element and append and replace it to the 'span' element. However i got the following error:
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
Here is my codes:
if ($("p:contains('computer forensics is')")) {
var highlight = document.createElement('span');
highlight.className = 'highlight';
highlight.style.backgroundColor = "red";
highlight.id = "";
highlight.setAttribute("title", "");
var node = $("p:contains('computer forensics is')");
var wordClone = node.clone(true);
highlight.appendChild(wordClone);
node.parentNode.replaceChild(highlight, node);
}
Make this line:
var wordClone = node.clone(true);
into this:
var wordClone = node.clone(true)[0]; // now it is HTMLElement
You were mixing jQuery objects with native elements.
Also I'm at a loss of words why you would not use jQuery when it is available.
You can rewrite most of the things in jQuery:
if ($("p:contains('computer forensics is')").length) {
var highlight = $('<span/>', {
"class": "higlight",
style: "background-color:red;"
});
var node = $("p:contains('computer forensics is')");
var wordClone = node.clone(true);
highlight.append(wordClone);
node[0].parentNode.replaceChild(highlight, node);
}
这篇关于jQuery克隆节点错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!