En mi sitio, tengo algunos enlaces que se construyen dinámicamente con JS. No todos contienen un valor href, por lo que agrego un valor href dinámicamente. Yo uso javascript:; como ese valor.
Ahora, necesito poder abrir todos los enlaces que no están en mi host en una nueva ventana. Obviamente, javascript:; no es mi host, por lo que cualquier enlace con eso en el atributo href se abrirá en una nueva ventana.
En el fragmento a continuación, trato de evitar que eso suceda, pero no obtengo el resultado que deseo.
¿Cómo envío todos los enlaces externos a una nueva pestaña, excepto uno que especifique?
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>Parece que esta fue la mejor solución...
Si inspecciona cada enlace, verá que el enlace externo tiene _blank , el enlace interno tiene _self y el que tiene href="javascript:;" tiene _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>