Categories
JavaScript Answers

How to call preventDefault() on an anchor element with JavaScript?

Spread the love

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.

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 *