Add links to text dynamically without changing element attributes

Asked

Viewed 36 times

1

I’m creating a tool to add a link to the text if it matches one of the titles in the object links, I’m using replace and regex, the problem is that in this way it affects the attributes of the elements that contain the desired text, I tried to use textContent in place of innerHTML, but thus the element a is returned in text format.

What should I do to add links to texts without affecting the integrity of HTML elements?

let conteudo = document.getElementById("conteudo");
let links = [
  {
    title: 'Teste',
    link: '/test.html'
  }
];

links.forEach(link => {
  conteudo.innerHTML = conteudo.innerHTML.replace(new RegExp( link.title, 'gi' ), `<a href="${link.link}">${link.title}</a>`);
});
<div id="conteudo">
  <img alt="Teste" src="/teste.jpg">
  <br><br>
  <div class="teste">
    Essa é uma frase de <span id="teste">teste</span>
  </div>
</div>

1 answer

0

I’m not sure I understand what you want, but here’s an explanation on how to turn pieces of text into a link, without changing the CSS format the simplest way I can!

First, you create, in your CSS scope, the characterization of the links, and try to get as close to the common text, with the same font, size, color, etc. It is important to specify as many things as possible possible, because HTML adopts a default already predefined in some characteristics.

According to, the element where your text is, be it a , a ,

... anyway, the object where your string will be stored.

It is important to make clear the specifications of ID or Class, for that you don’t end up getting confused later.

Third, program your script, which will only have 3 clear tasks:

  1. Receive the text object as input as soon as loaded on the page;
  2. Loop text object and compare with the titles of securities object
  3. Replace the value that, when compared, returns true.

Having explained this, it then follows a script model.

const keywords = 
[
{title: 'Jogos', link: 'https://pt.wikipedia.org/wiki/Desporto'}
]

function update_text(txt, id){

/// recebe txt como o corpo do texto e id como ID do texto

    let txt_elements = []
    txt_elements = txt.split(' '); // separa o texto em palavras
  
  /// loop pelos elementos do texto
  for(let i = 0; i < txt_elements.length-1; i++){
    
    if(txt_elements[i] === keywords[0].title){ // elemento bate com a pesquisa
      txt_elements.splice(i, 1, `<a class='link-pattern' href='${keywords[0].link}'>${keywords[0].title}</a>`) // modifica elementos
    }

  }
  
  txt = txt_elements.join(' '); // txt recebe elementos modificados
  document.querySelector(`#${id}`).innerHTML = txt; // muda texto em HTML para o que há dentro da variável txt
}
#test-content {
  font-family: Verdana;
  font-size: 10px;
  color: rgb(20, 20, 20)
}

.link-pattern {
  font-family: Verdana;
  font-size: 10px;
  color: rgb(20, 20, 20);
  text-decoration: none
}
<!DOCTYPE html>
<html>
<head>
    <title>Teste</title>
</head>
<body>

    <p id='test-content' onmouseover='update_text(this.innerHTML, this.id)'>Os Jogos têm crescido em escala, a ponto de quase todas as nações serem representadas. Tal crescimento tem criado inúmeros desafios, incluindo boicotes, doping, corrupção de agentes públicos e terrorismo. A cada dois anos, os Jogos Olímpicos e sua exposição à mídia proporcionam a atletas desconhecidos a chance de alcançar fama nacional e, em casos especiais, a fama internacional. Os Jogos também constituem uma oportunidade importante para a cidade e o país se promover e mostrar-se para o mundo.</p>

</body>
</html>

Ready, from now on your code automatically replaces common strings for links :D

(If the answer has helped, please mark your question as Answered kskssksk)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.