Search code examples
htmlhyperlinkattributeshref

How to set parameter and its value to HREF dynamic using javascript


I have a link like following

<a id="dynamicLink" href="http://www.w3schools.com?userName=test">Visit W3Schools</a>

I would like to change the value of userName from test to test1.

How to do that using javascript?

could someone help me on this?


Solution

  • I suggest using a library to work with URIs. It will provide some consistency. Here is an example using URI.js:

    // Get our <a> element
    var l = document.getElementById('dynamicLink');
    
    // Use URI.js to work with the URI
    // http://medialize.github.io/URI.js/
    var uri = URI(l.href);
    
    // Get the query string as an object
    var qs = uri.query(true);
    
    // Change our value
    qs.userName = 'test1'
    
    // Update the URI object
    uri.query(qs);
    
    // Set our new HREF on the <a> element
    l.href = uri;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.15.2/URI.min.js"></script>
    
    <a id="dynamicLink" href="http://www.w3schools.com?userName=test&someOtherKey=val">Visit W3Schools</a>