Как заменить слово гиперссылкой с помощью javascript?

Я хочу заменить слово [ТОЛЬКО 1 РАЗ], в моем случае «Роналдо», гиперссылкой на КАЖДЫЙ пост на моем сайте. Итак, я использовал следующий код.

document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href = "www.ronaldo.com">Ronaldo</a>');

Это действительно работало хорошо, пока я не заметил проблему.

Он даже заменяет слово «Роналду» на post-title, когда я хочу, чтобы оно заменяло слово только в post-body.

Вот мельком мой код, чтобы вы могли лучше понять.

https://codepen.io/vkdatta27/pen/rNMGbmj [ОБНОВЛЕНО]

Было бы очень полезно, если бы кто-то сказал, как решить эту проблему. Я помечаю jquery и ajax, потому что они тоже знают javascript.

ПРИМЕЧАНИЕ: ДО СЕГОДНЯ МЫ НЕ ИСПОЛЬЗОВАЛИ НИКАКИХ КЛАССОВ, IDS, ТЕГОВ, ТАКИХ POST-BODYP, КРОМЕ POST-TITLE ДЛЯ ЦЕЛИ ФОРМАТИРОВАНИЯ

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
3
0
441
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Предположим, что ваши элементы post-body не имеют имен классов, мы можем запросить их с помощью .getElementsByTagName(), а затем заменить текст ссылкой.

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>

Здравствуйте, Харшана.

Kraken 24.12.2020 09:38

Я не использую никаких тегов, классов, идентификаторов, кроме .post-title

Kraken 24.12.2020 09:38

Вам нужно использовать replaceAll вместо replace

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

Или вы можете использовать regex (это также будет работать как замена без учета регистра) -

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

И если вы не хотите менять текст в классе post-title, вы можете использовать селектор запросов not -

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>');

Это выберет только первый p, у которого нет класса post-title.

Если у вас есть не только теги p, используйте querySelectorAll, а затем повторите это, чтобы заменить текст.

В качестве альтернативы вы можете добавить другой класс к своему контенту и использовать этот класс в селекторе запросов.

Привет, Нихил, я хочу заменить только ОДНО вхождение в теле сообщения. ReplaceAll и Regex не подходит. Кроме того, я не использую тег <p> в своих сообщениях. Итак, `p:not(.post-title) не работает.

Kraken 24.12.2020 09:35

Не захватывайте весь контент из DOM, если вы не хотите изменять весь документ. Вы сказали, что просто хотите изменить пост-тело. Итак, дайте идентификатор для тела сообщения (чтобы мы могли получить тело сообщения в js) и измените только его содержимое.

Примечание. Чтобы заменить все вхождения «Роналду», используйте функцию replaceAll("word to replace").

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>

Просто чистая версия 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);

Просто измените

документ.тело

к

document.getElementById("ID")//соответствующий идентификатор элемента, т.е. ваш абзац

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>
Ответ принят как подходящий

Попробуй это -

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>

Другие вопросы по теме