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

275
Vistas
JavaScript: get href value of multiple <a> tags

Without using jQuery or any other library, the objective is to inform the user which URL will visit with an alert event. In the markup, there are multiple <a> tags with different href values for each, when the user clicks the <a> tag, an alert event displays mentioning where the user is going before actually leaving the website.

Workflow:

  1. The document loads
  2. The user clicks an <a> tag
  3. An alert event displays with the href value of the clicked <a> tag
  4. Once the user closes the alert event, the browser starts loading the href website

Code sample:

document.querySelector('a').onclick = function(e) {
    e.preventDefault();
    var href = document.querySelector('a').href;
    alert('You are going to: ' + href);
    window.location = href;
}
<div id="container">
  <a class="link" href="https://www.microsoft.com/">Link A</a>
  <a class="link" href="https://www.google.com/">Link B</a>
  <a class="link" href="https://www.apple.com/">Link C</a>
</div>

Objective:

  • Set up the JavaScript dynamically for all the <a> tags to achieve the workflow output for each one of them (and for any further <a> tags with the same class that might be included in the document). Please note that only Link A works as desired so far.

Your coding to solve this is appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use querySelectorAll() to get all the anchor tags, then loop through them and addEventListener() instead of onclick, because onclick can only be assigned to one element at a time. Also, you can grab the href with e.target.href. e.target is the element that was acted upon to start the event.

document.querySelectorAll('a').forEach(function(el) {
    el.addEventListener("click", function(e) {
        if (e.target.matches('.link')) {
          e.preventDefault();
          var href = e.target.href;
          alert('You are going to: ' + href);
          //window.location = href;
       }
    })
})
<div id="container">
  <a class="link" href="https://www.microsoft.com/">Link A</a>
  <a class="link" href="https://www.google.com/">Link B</a>
  <a class="link" href="https://www.apple.com/">Link C</a>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

querySelector will only match the first element that matches the selector. You can either use querySelectorAll to match all of those elements, add listeners to all of them...

OR

Attach one listener to the container (event delegation allows it to capture events from its children as they "bubble up" the DOM). When a child element is clicked the handler function checks that its an anchor with a .link class, and then executes the rest of the code.

const container = document.querySelector('#container');
container.addEventListener('click', handleClick);

function handleClick(e) {
  if (e.target.matches('.link')) {
    e.preventDefault();
    const { href } = e.target;
    alert(`You are going to: ${href}`);
    window.location = href;
  }
}
<div id="container">
  <a class="link" href="https://www.microsoft.com/">Link A</a>
  <a class="link" href="https://www.google.com/">Link B</a>
  <a class="link" href="https://www.apple.com/">Link C</a>
</div>

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