How to get HTML a tag working with href and onclick with JavaScript?

Sometimes, we want to get HTML a tag work with href and onclick with JavaScript.

In this article, we’ll look at how to get HTML a tag work with href and onclick with JavaScript.

How to get HTML a tag working with href and onclick with JavaScript?

To get HTML a tag work with href and onclick with JavaScript, we can handle the navigation and clicks with the click handler.

For instance, we write

<a id="myButton" href="http://example.com">Click me!</a>

to add a link.

Then we write

document.querySelector("#myButton").addEventListener("click", (e) => {
  e.preventDefault();
  window.location = e.target.href;
});

to select the link with querySelector.

And we call addEventListener with 'click' and the click event handler callback.

In it, we call preventDefault to prevent the default navigation behavior of going to the URL set as the href attribute value.

And then we go to the href URL with

window.location = e.target.href

Conclusion

To get HTML a tag work with href and onclick with JavaScript, we can handle the navigation and clicks with the click handler.