I wrote this function which takes in a word as input and puts it in a tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the tag arround it.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1$2$3');
}
On providing the value and input, e.g. "message" and "This is a test message":
The output is: This is a test message
The desired output is: This is a test message
Even replacing the value with value.bold(), returns the same thing.
EDIT
This is the HTML together with the JS that I m working on:
Testfunction myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; 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
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1$2$3'));
}
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.
Is it possible there is something wrong with the way I'm taking back what the function is returning to me?
This is what I do:
children[child].nodeValue = output;
解决方案
You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement
children[child].nodeValue= output;
by the following:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);