X
X
xamer202022-04-12 16:44:59
HTML
xamer20, 2022-04-12 16:44:59

How to auto-replace all links in the code?

There is a site on which there are a lot of links, you need to make sure that when you click on them, all links are redirected or replaced with another one. Here is a code example of how it is implemented, but it only works with the first link on the site, I tried to insert querySelectorAll, but it does not work.

HTML:
<a href="https://example.com">link</a>
JS:
document.querySelector('a').addEventListener('click', (e) => {
  e.preventDefault()
  window.open('https://anotherLink.com')
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Olga, 2022-04-12
@xamer20

The most normal option is to do redirects through htaccess.
If the path is "js only":

let links=document.querySelectorAll('a');//находим все ссылки
for(var i = 0; i < links.length; i++) {//проходимся циклом
  links[i].href="https://anotherLink.com"; //заменяем ссылки
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question