I want to replace a word [ONLY 1 TIME], in my case ‘Ronaldo’, with hyperlink on EVERY post on my site. So, I used the following code.
document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>');
That really worked well until i noticed the issue.
It’s even replacing the word ‘Ronaldo’ on post-title
when i want it to replace the word in post-body
only.
Here’s a glimpse of my code so you can have a better understanding.
https://codepen.io/vkdatta27/pen/rNMGbmj [UPDATED]
It would be very helpful if someone says a way to fix this issue. I’m tagging jquery and ajax because they too know javascript.
NOTE: UNTIL NOW, WE DIDN’T USE ANY CLASSES, IDS, TAGS LIKE POST-BODY
P
EXCEPT POST-TITLE
FOR FORMATTING PURPOSE
5
Answers
Assume that your
post-body
elements don’t have any class names, we can query them by using.getElementsByTagName()
and then replace the text with linkYou need to use
replaceAll
instead ofreplace
Or you can use
regex
(this will also work as case insensitive replace) –And If you do not want to change the text in class
post-title
you can usenot
query selector –This will only select first
p
which does not have classpost-title
.If you have more than just
p
tags, then usequerySelectorAll
and then iterate over this to replace text.Alternatively, you can add different class to your content and use this class in query selector.
Don’t grab whole content from DOM if you don’t want to change whole document. You said you just want to change post-body. So Give a id to post body (so we can grab post-body in js) and change only it’s content.
Note: To replace all "Ronaldo" occurrences, use
replaceAll("word to replace")
function.Just the clean version of above snippet’s js.
Just change
to
Try this –