Kraken
Kraken

Reputation: 91

How to replace a word with hyperlink using javascript?

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

Upvotes: 2

Views: 915

Answers (5)

G G
G G

Reputation: 147

Try this -

postBodyElems = document.getElementsByTagName("p");
for (var i = 0; i < postBodyElems.length; i++) {
  if (postBodyElems[i].className == '') {
    postBodyElems[i].innerHTML = postBodyElems[i].innerHTML.replace('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');
  }
}
.post-title {
  font-size: 20px;
}

.warning {
  color: red;
}

a {
  color: blue;
}
<p class='post-title'>Ronaldo became the hottest player of 2020</p>
<p>Ronaldo [<span class='warning'>I want this text to turn into a hyperlink</span>] dos Santos Aveiro GOIH ComM (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaɫdu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for Serie
  A club Juventus and captains the Portugal national team. Often considered the best player in the world and widely regarded as one of the greatest players of all time,[10] Ronaldo has won five Ballon d'Or awards[note 3] and four European Golden Shoes,
  both of which are records for a European player. He has won 30 major trophies in his career, including seven league titles, five UEFA Champions Leagues, one UEFA European Championship, and one UEFA Nations League title. Ronaldo holds the records for
  the most goals (134) and assists (41) in the history of the UEFA Champions League.[11] He is one of the few recorded players to have made over 1,000 professional career appearances and has scored over 750 senior career goals for club and country.[12]
  He is also the second player to score 100 international goals, and the first European to achieve the feat.[13]</p>

Upvotes: 1

Ejilarasan J
Ejilarasan J

Reputation: 320

Just change

document.body

to

document.getElementById("ID") //respective element id i.e your paragraph

document.getElementById("post-body").innerHTML = document.getElementById("post-body").innerHTML.replaceAll('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');
.post-title{
  font-size:20px;
  }
.warning{
 color:red;
  }
a{
  color:blue;
  }
<p class='post-title'>Ronaldo became the hottest player of 2020</p>
<p id='post-body'>Ronaldo [<span class='warning'>I want this text to turn into a hyperlink</span>] dos Santos Aveiro GOIH ComM (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaɫdu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for Serie A club Juventus and captains the Portugal national team. Often considered the best player in the world and widely regarded as one of the greatest players of all time,[10] Ronaldo has won five Ballon d'Or awards[note 3] and four European Golden Shoes, both of which are records for a European player. He has won 30 major trophies in his career, including seven league titles, five UEFA Champions Leagues, one UEFA European Championship, and one UEFA Nations League title. Ronaldo holds the records for the most goals (134) and assists (41) in the history of the UEFA Champions League.[11] He is one of the few recorded players to have made over 1,000 professional career appearances and has scored over 750 senior career goals for club and country.[12] He is also the second player to score 100 international goals, and the first European to achieve the feat.[13]</p>

Upvotes: 0

cipherdragon
cipherdragon

Reputation: 373

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.

document.getElementById("post-body").innerHTML = document.getElementById("post-body").innerHTML.replaceAll('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');
.post-title {
  font-size: 20px;
}

.warning {
  color: red;
}

a {
  color: blue;
}
<p class='post-title'>Ronaldo became the hottest player of 2020</p>

<!--Give the following p element an id, so we can get that element in js. I gave the 'post-body' id. -->
<p id='post-body'>Ronaldo [<span class='warning'>I want this text to turn into a hyperlink</span>] dos Santos Aveiro GOIH ComM (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaɫdu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for Serie
  A club Juventus and captains the Portugal national team. Often considered the best player in the world and widely regarded as one of the greatest players of all time,[10] Ronaldo has won five Ballon d'Or awards[note 3] and four European Golden Shoes,
  both of which are records for a European player. He has won 30 major trophies in his career, including seven league titles, five UEFA Champions Leagues, one UEFA European Championship, and one UEFA Nations League title. Ronaldo holds the records for
  the most goals (134) and assists (41) in the history of the UEFA Champions League.[11] He is one of the few recorded players to have made over 1,000 professional career appearances and has scored over 750 senior career goals for club and country.[12]
  He is also the second player to score 100 international goals, and the first European to achieve the feat.[13]</p>

Just the clean version of above snippet's js.

const postBody = document.getElementById("post-body");
const ronaldoLink = '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>'

postBody.innerHTML = postBody.innerHTML.replaceAll('Ronaldo', ronaldoLink);

Upvotes: 1

Nikhil Patil
Nikhil Patil

Reputation: 2540

You need to use replaceAll instead of replace

document.body.innerHTML = document.body.innerHTML.replaceAll('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');

Or you can use regex (this will also work as case insensitive replace) -

document.body.innerHTML = document.body.innerHTML.replace(/Ronaldo/gi, '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');

And If you do not want to change the text in class post-title you can use not query selector -

document.querySelector("p:not(.post-title)").innerHTML = 
document.querySelector("p:not(.post-title)").innerHTML.replaceAll('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');

This will only select first p which does not have class post-title.

If you have more than just p tags, then use querySelectorAll and then iterate over this to replace text.

Alternatively, you can add different class to your content and use this class in query selector.

Upvotes: 0

Harshana
Harshana

Reputation: 5486

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 link

postBodyElems = document.getElementsByTagName("p");
for (var i = 0; i < postBodyElems.length; i++) {
  if (postBodyElems[i].className == '') {
    postBodyElems[i].innerHTML = postBodyElems[i].innerHTML.replace('Ronaldo', '<a href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo">Cristiano Ronaldo</a>');
  }
}
.post-title {
  font-size: 20px;
}

.warning {
  color: red;
}

a {
  color: blue;
}
<p class='post-title'>Ronaldo became the hottest player of 2020</p>
<p>Ronaldo [<span class='warning'>I want this text to turn into a hyperlink</span>] dos Santos Aveiro GOIH ComM (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaɫdu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for Serie
  A club Juventus and captains the Portugal national team. Often considered the best player in the world and widely regarded as one of the greatest players of all time,[10] Ronaldo has won five Ballon d'Or awards[note 3] and four European Golden Shoes,
  both of which are records for a European player. He has won 30 major trophies in his career, including seven league titles, five UEFA Champions Leagues, one UEFA European Championship, and one UEFA Nations League title. Ronaldo holds the records for
  the most goals (134) and assists (41) in the history of the UEFA Champions League.[11] He is one of the few recorded players to have made over 1,000 professional career appearances and has scored over 750 senior career goals for club and country.[12]
  He is also the second player to score 100 international goals, and the first European to achieve the feat.[13]</p>

Upvotes: 1

Related Questions