Categories
JavaScript Answers

How to add href attribute to a link dynamically using JavaScript?

Spread the love

Sometimes, we want to add href attribute to a link dynamically using JavaScript.

In this article, we’ll look at how to add href attribute to a link dynamically using JavaScript.

How to add href attribute to a link dynamically using JavaScript?

To add href attribute to a link dynamically using JavaScript, we can set the link’s href property.

For instance, we write

const a = document.getElementById("yourlinkId");
a.href = "http://example.com";

to select the link with getElementById.

Then we set the href attribute of the link by settings its href property.

Conclusion

To add href attribute to a link dynamically using JavaScript, we can set the link’s href property.

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 *