Categories
JavaScript Answers

How to change href of an a tag on button click with JavaScript?

Spread the love

Sometimes, we want to change href of an a tag on button click with JavaScript

In this article, we’ll look at how to change href of an a tag on button click with JavaScript.

How to change href of an a tag on button click with JavaScript?

To change href of an a tag on button click with JavaScript, we can set the href property of the anchor element.

For instance, we write

<a href="#" id="abc">foo</a> <a href="#" id="myLink">bar</a>

to add 2 anchor elements.

Then we write

document.getElementById("myLink").onclick = (e) => {
  e.preventDefault();
  document.getElementById("abc").href = "example.com";
};

to get the anchor element with ID myLink with

document.getElementById("myLink")

Then we set its onclick property to a function that changes the href attribute of the anchor element with ID abc on click with

document.getElementById("abc").href = "example.com";

We call preventDefault to stop the default behavior of the link, which is to navigate to the URL set as the value of the href attribute.

Then we can run the rest of the code in the function.

Conclusion

To change href of an a tag on button click with JavaScript, we can set the href property of the anchor element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *