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

274
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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