Access data-id of clicked anchor tag and also redirect to href path using JavaScript

Viewed 16

I want to apply click event on anchor tags but when I click on first then get the data-id value of first and also redirect to href value similarly if I click on second link then get the data-id of second link only and redirect to its href value.

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>

  <body>
    <a href="2.html?a=1" data-id="1" class="link">One</a>
    <a href="2.html?a=2" data-id="2" class="link">Two</a>
    <a href="2.html?a=3" data-id="3" class="link">Three</a>
    <script>
      const body = document.querySelector('body');
      body.onclick = (e) => {
        e.preventDefault();
        let link = body.querySelector('.link');
        console.log(link);
      }
    </script>
  </body>

</html>

This is the code I'm trying but when I click on any of the anchor tag then only first anchor tag accessing.

1 Answers

This is what I did and now it's working perfect.

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>

  <body>
    <a href="2.html?a=1" data-id="1">One</a>
    <a href="2.html?a=2" data-id="2">Two</a>
    <a href="2.html?a=3" data-id="3">Three</a>
    <script>
      const body = document.querySelector('body');
      body.onclick = (e) => {
        e.preventDefault();
        let anc = e.target;
        const data = {
          a: anc.getAttribute('data-id')
        }
        localStorage.setItem('data', JSON.stringify(data));
        window.location = anc.getAttribute('href');
      }
    </script>
  </body>

</html>

Related