jQuery克隆节点错误 [英] jQuery clone node error

查看:107
本文介绍了jQuery克隆节点错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


未捕获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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆