I m new to javascript and would be great if you could help me with this issue I m facing.
In the HTML code below, I m trying to highlight a particular word(say “message”)by replacing the word by appending to it to make it bold.
<body>
<img src="http://some.web.site/image.jpg" title="abcd" />
This is a test message.
</body>
The String “This is a test message” is found directly in the body element(so there is no id, and hence no getElementById can be used to extract the text).
So I got the entire body element and extracted the text by using textContent.(this gave me the text and ignored the image that is above the text in the html.)
Then after highlighting the word I set the ‘body’s textContent back to the new String.
The problem is that now I m not able to preserve the image that was above the text, and the new body has only the value of the textContent in it, and the image is lost. This is the JS I used(but now I m replacing message with the word phone).
<script>
function myFunction(){
var x = document.getElementsByTagName('body')[0].textContent;
var v = x.replace("message","phone");
document.getElementsByTagName('body')[0].textContent = v;
}
</script>
Is there any other way to replace text that is placed directly under the body, which has other elements too?
In order to do something like this, you would need to loop through all text nodes in the document, search for the word, and wrap it.
Something like this:
That should do it. To use, just call
highlight("message"), with whatever text you want. Note that this will be case-sensitive – if you need caseless matching, let me know and I’ll edit to take that into account (although for the most part you could probably get away withhighlight("message"); highlight("Message");)Also, you can limit the search to a particular element. Let’s say you have
<div id="replace-me">, you can limit the search to that element like so:(You can use any way to get the node, this is just the easiest)