javascript – Is it necessary to put a href attribute to an a tag?

Question:

I'm using a tag with an onclick but I do not know if I'm doing well or really the right way is using a href without need.

Answer:

If you check the specification right here you will notice how:

An element that is of type a has the possibility of including an attribute of type href which serves to link to a URL as an external resource that has to be consumed when clicking on the text that you place between the opening and closing of said tag; more or less so:

<a href="algunsitio.com">Ir a algún sitio</a>

So it is not so much that what you do to give an action in the click event is incorrect, but rather that this other because if we include this attribute we obtain the same functionality

Consider that if you are going to use this event, it would be more convenient or logical for situations in which, for example, you try to manipulate the data that is entered into an input and therefore you will carry out one or more actions in consequence.

Specifically, if we look at this standard, you will be able to read and I quote:

The href attribute on a and area elements is not required, when those elements do not have the href attribute they do not create hyperlinks.

So to the question, it is not necessary, but using JS to give that effect is to add, I consider, extra complexity that you will be able to achieve with a simple attribute that exists natively.

Scroll to Top