ronish
ronish

Reputation: 568

jQuery clone node error

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

Answers (3)

Roko C. Buljan
Roko C. Buljan

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:

jsBin demo

$.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');

enter image description here

Upvotes: 1

Amit Joki
Amit Joki

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

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

You can't have paragraphs in spans (invalid HTML()), but assuming you want spans in your paragraphs instead:

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);
    }
});

Upvotes: 1

Related Questions