Make HTML text bold
I wrote this function that takes a word as input and puts it in a tag <b>
so it is bold when rendered in HTML. But when it actually does, the word is not in bold, but only has a tag <b>
.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
When providing value and input, eg. "message" and "This is a test message":
Conclusion: This is a test <b>message</b>
Desired output:This is a test message
Even replacing the value with value.bold()
, returns the same.
EDIT This is the HTML along with the JS I'm working on:
<!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="knorex"/>
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
Basically I am getting the result of the delimiter function and modifying the nodeValue
child node.
Is it possible that there is something wrong with the way I return what the function returns to me?
This is what I am doing:
children[child].nodeValue = output;
source to share
You want the markup to be treated like HTML, not just replaced with existing content in the text node. To do this, replace the operator
children[child].nodeValue= output;
in the following way:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);
source to share