jQuery克隆节点错误

我必须检查’p’元素是否包含一些文本,如果是,则创建另一个元素’span’然后克隆’p’元素并追加并将其替换为’span’元素。 但是我收到以下错误:

Uncaught NotFoundError:无法在’Node’上执行’appendChild’:新的子元素为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); } 

建立这一行:

 var wordClone = node.clone(true); 

进入这个:

 var wordClone = node.clone(true)[0]; // now it is HTMLElement 

您将jQuery对象与本机元素混合在一起。

另外,我不知道为什么你不能使用jQuery。

你可以在jQuery中重写大部分内容:

 if ($("p:contains('computer forensics is')").length) { var highlight = $('', { "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); } 

您不能在跨度中使用段落(无效的HTML()),但假设您希望在段落中使用跨度:

JSFiddle: http : //jsfiddle.net/TrueBlueAussie/Kw3tj/2/

 $(function () { var $node = $("p:contains('computer forensics is')"); if ($node.length) { var $highlight = $('', { "class": "highlight", style: "background-color: red" }); $highlight.html($node.html()); $node.empty().append($highlight); } }); 

注意:如果要定位的文本包含在其他HTML元素中的部分,则下面的代码不起作用:
computer forensics is

您需要的是突出显示一些特定的文本部分?
创建自己的微插件:

jsBin演示

 $.fn.highlight = function(word){ return this.each(function(){ var span = $('', { 'class' : "", 'html' : word, 'id' : "", 'title' : "", 'style' : "color:white; background:red" }), $el = $(this), reg = new RegExp(word, 'ig'); $el.html($el.html().replace(reg, span.prop('outerHTML'))); }); }; // /////// // USE EXAMPLE: $('p').highlight('computer forensics is'); 

在此处输入图像描述