-1

I am trying to add an id to my href using jQuery/Javascript:

This is my HTML:

<a href="product#=" id="39">Test</a>

What am trying to achieve is this:

<a href="product#=39" id="39">Test</a>

Basically just want to add this ID to href,

So far a manage to do this:

var link = $('a');
link.attr('href', link.attr('href') + '39');

This is ok but If I have more links, this will not work because the value is hardcoded,

Can anybody try to help me with this

Ivan Nukli
  • 57
  • 4
  • 1
    Take a look at [$.each](https://api.jquery.com/each/) if you are using jQuery, or [loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) if you are using plain JavaScript. – yqlim Aug 02 '21 at 14:10

1 Answers1

0

You can use the .each() jquery function to go with your $('a') selector....

<html>

<head>
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <a href="product#=" id="39">Test</a>
  <a href="product#=" id="40">Test</a>
  <a href="product#=" id="41">Test</a>
  <a href="product#=" id="42">Test</a>
  <script>
    $('a').each(function() {
      this.href = 'product#=' + this.id;
    });
  </script>
</body>

</html>
DynasticSponge
  • 1,416
  • 2
  • 9
  • 13