Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda