Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
¿Cómo abrir todos los enlaces externos en una nueva ventana, excepto href específico?

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!