Sometimes, we want to call preventDefault() on an anchor element with JavaScript.
In this article, we’ll look at how to call preventDefault() on an anchor element with JavaScript.
How to call preventDefault() on an anchor element with JavaScript?
To call preventDefault() on an anchor element with JavaScript, we can call preventDefault
in an event handler function.
For instance, we write
<a href="#">Click Me</a>
to add an anchor element.
Then we write
const a = document.querySelector("a");
a.onclick = (event) => {
event.preventDefault();
};
to select the anchor element with querySelector
.
And then we set a.onclick
to a function that runs when we click on the anchor element.
In it, we call event.preventDefault
to prevent the default behavior of the element.
Conclusion
To call preventDefault() on an anchor element with JavaScript, we can call preventDefault
in an event handler function.