3

I want to add parameters to anchor tag via JavaScript. I do not want to use jQuery for this purpose. Here is my html anchor tag

<div class="u-right u-half"><a href="http://example.com/register/" class="u-button u-alt">Register</a></div>

I am able to do this with jquery but I want to do this with JavaScript. Here is my jquery but I want to use JavaScript instead

jQuery('.u-right .u-button').attr("href", function(i, href) {
return href + '?page=search';
});

How I can do this with JavaScript ?

wplearner
  • 405
  • 6
  • 19

3 Answers3

3

document.getElementById("placeholder").href += '?page=search';
<div class="u-right u-half" id="placeholder">
  <a href="http://example.com/register/" class="u-button u-alt">Register</a>
</div>
Mr. Roshan
  • 1,777
  • 13
  • 33
  • You should avoid answering duplicate questions. https://stackoverflow.com/questions/17155135/how-can-the-value-of-an-href-attribute-be-changed-using-javascript-css – Ankit Agarwal Aug 22 '18 at 06:31
  • Yup @AnkitAgarwal I didn't Observed that!! – Mr. Roshan Aug 22 '18 at 06:32
  • Thank you for your help. I have tried this code but it is causing an error. Uncaught TypeError: Cannot read property 'href' of null. Why it is causing this error. – wplearner Aug 22 '18 at 06:37
  • had you added id="placeholder" into your element? @Awan. – Mr. Roshan Aug 22 '18 at 07:11
  • No I did not, Actually I am using document.querySelector('.u-right .u-button').href += '?page=search'; – wplearner Aug 22 '18 at 11:32
  • 1
    I have fixed this issue and for this I added document.addEventListener("DOMContentLoaded", function(){ }); around my code and now it is working perfectly. Thank you! – wplearner Aug 22 '18 at 12:47
2

Using getElementsByClassName() and setAttribute() you can do like below

var anchor = document.getElementsByClassName('u-button')[0];
anchor.setAttribute('href', anchor + '?page=search')

console.log(anchor);
<div class="u-right u-half"><a href="http://example.com/register/" class="u-button u-alt">Register</a></div>
Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56
1

To make that happen for all anchors/elements that match some css selector:

[...document.querySelectorAll('.u-right .u-button')]
  .forEach(node => node.href += '?page=search')

Old School js:

Array.prototype.slice.call(document.querySelectorAll(…))
  .forEach(function (node) { … });
philipp
  • 15,947
  • 15
  • 61
  • 106