我必须检查'p‘元素是否包含一些文本,如果是这样,请创建另一个元素'span’,然后克隆'p‘元素并将其追加到'span’元素中,并将其替换为‘span’元素。但是,我得到了以下错误:
Uncaught :在‘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);
}
发布于 2014-05-29 10:50:47
做这一行:
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 = $('<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);
}
发布于 2014-05-29 11:23:07
您不能在span中包含段落(无效的HTML()),但是假设您希望段落中包含跨段:
JSFiddle:http://jsfiddle.net/TrueBlueAussie/Kw3tj/2/
$(function () {
var $node = $("p:contains('computer forensics is')");
if ($node.length) {
var $highlight = $('<span/>', {
"class": "highlight",
style: "background-color: red"
});
$highlight.html($node.html());
$node.empty().append($highlight);
}
});
https://stackoverflow.com/questions/23931579
复制相似问题