ArticleZip > How To Change Href Of Tag On Button Click Through Javascript

How To Change Href Of Tag On Button Click Through Javascript

Changing the href of a tag on button click through JavaScript can be a great way to dynamically update the destination URL of a link based on user interaction. By utilizing JavaScript, you can easily manipulate the href attribute of an anchor tag when a button is clicked, providing a seamless user experience on your website or web application.

To achieve this functionality, you'll need a basic understanding of HTML, CSS, and JavaScript. Let's dive into a step-by-step guide on how to implement this feature effectively:

1. HTML Structure: Begin by setting up your HTML structure. Create an anchor tag (``) with an initial href attribute that points to a default URL. Additionally, include a button (`

<title>Change Href on Button Click</title>


    <a href="https://www.example.com" id="myLink">Visit Example</a>
    <button id="myButton">Change Link</button>

    
        const button = document.getElementById('myButton');
        const link = document.getElementById('myLink');

        button.addEventListener('click', function() {
            link.setAttribute('href', 'https://www.newlink.com');
        });

In this example, when the button is clicked, the href attribute of the anchor tag is updated to `https://www.newlink.com`. You can customize this code further to suit your specific requirements.

By following these steps, you can easily change the href of a tag on button click through JavaScript, adding interactivity and dynamic functionality to your web projects. Experiment with different scenarios and enhance your user experience with this practical technique.

×