Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
How to open all offsite links in a new window except for specific href?

On my site, I have some links that are built dynamically with JS. Not all of them contain an href value, so I add an href value dynamically. I use javascript:; as that value.

Now, I need to be able to open all links not on my host in a new window. Obviously, javascript:; is not my host, so any link with that in the href attribute will open in a new window.

In the snippet below, I'm trying to prevent that from happening, but I'm not getting the result I desire.

How do I push all offsite links to a new tab, except for one that I specify?

document.querySelectorAll("a:not(a[href])").forEach(element => {
  element.setAttribute("href", "javascript:;")
});

var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
  var a = all_links[i];
  if (a.hostname != location.hostname || a.getAttribute("href") !== 'javascript:;') {
    a.rel = 'noopener';
    a.target = '_blank';
  }
}
<a href="https://yahoo.com">Yahoo!</a>
<hr>
<a>something else</a>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Looks like this was the best solution...

If you inspect each link, you'll see that the external link has _blank, the internal link has _self, and the one with href="javascript:;" has _self.

document.querySelectorAll("a:not(a[href])").forEach(element => {
  element.setAttribute("href", "javascript:;")
});

let all_links = document.querySelectorAll('a');

for (var i = 0; i < all_links.length; i++) {
  let anchors = all_links[i];
  if (anchors.getAttribute('href') == 'javascript:;' || anchors.hostname == location.hostname) {
    anchors.target = "_self";
  } else {
    anchors.target = "_blank";
  }
}
<a href="https://yahoo.com">External Link (Yahoo!)</a>
<hr>
<a href="/questions/69563273/change-the-font-and-the-line-spacing-of-a-style">Change the font and the line spacing of a style (SO Question)</a>
<hr>
<a>anchor without href (Goes nowhere)</a>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda