Bold text in body using javascript

This code tries to highlight (by adding a "bold" tag) some of the characters that are in the HTML body. (They are specified in the JS function) But instead of the text getting bold, I get the "bold" tag as the result in the html page that gets rendered.

As long as I want something like

This is a test message

I get

This is a test <b>message</>

      

Any help would be awesome.

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>

<script>

function myFunction(){
        var children = document.body.childNodes;
    for(var len = children.length, child=0; child<len; child++){
     if (children[child].nodeType === 3){ // textnode
        var highLight = new Array('abcd', 'edge', 'rss feeds');
        var contents = children[child].nodeValue;
        var output = contents;
        for(var i =0;i<highLight.length;i++){
            output = delimiter(output, highLight[i]); 
        }


    children[child].nodeValue= output; 
    }
    }
}

function delimiter(input, value) {
    return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>



</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>

These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss

<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>

      

+3


source to share


2 answers


The problem is that you are putting HTML in the text node, so it is evaluated strictly as text. One simple solution would be to just work with the innerHTML of the body element, e.g .:



<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>

<script>

function myFunction(){
  var highLight = ['abcd', 'edge', 'rss feeds'],
      contents = document.body.innerHTML;

  for( i = 0; i < highLight.length; i++ ){
    contents = delimiter(contents, highLight[i]); 
  }

  document.body.innerHTML = contents;
}

function delimiter(input, value) {
  return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>



</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>

These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss

<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>

      

+2


source


TextNode cannot have children, so it must be replaced in one way;

Replace

children[child].nodeValue = output;

      



FROM

var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);

      

+1


source