Categories
JavaScript Answers

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

Spread the love

To add "href" attribute to a link dynamically using JavaScript, we call the setAttribute method.

For instance, we write

const a = document.getElementById("link");
a.setAttribute("href", url);

to select the link with getElementById.

Then we call setAttribute to set the href attribute value to url.

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 *