Reputation: 568
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);
}
Upvotes: 0
Views: 4633
Reputation: 206593
Note: the code below does not work if the text to target has portions wrapped in other HTML elements like:
computer <i>forensics</i> is
All you need is to highlight some specific text portions?
Create your own micro-plugin:
$.fn.highlight = function(word){
return this.each(function(){
var span = $('<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');
Upvotes: 1
Reputation: 59292
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);
}
Upvotes: 3
Reputation: 93611
You can't have paragraphs in spans (invalid HTML()), but assuming you want spans in your paragraphs instead:
$(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);
}
});
Upvotes: 1