Categories
JavaScript Answers

How to get a button element to link to a location without an anchor element with JavaScript?

Spread the love

Sometimes, we want to get a button element to link to a location without an anchor element with JavaScript.

In this article, we’ll look at how to get a button element to link to a location without an anchor element with JavaScript.

How to get a button element to link to a location without an anchor element with JavaScript?

To get a button element to link to a location without an anchor element with JavaScript, we set the location on click.

For instance, we write

const gotoUrl = () => {
  window.location.assign("https://www.example.com/");
};

document.getElementById("button").addEventListener("click", gotoUrl);

to get the button with getElementById.

Then we call addEventListener to add the gotoUrl click listener to it.

In gotoUrl, we call window.location.assign to go to the URL on click.

Conclusion

To get a button element to link to a location without an anchor element with JavaScript, we set the location on click.

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 *