Search code examples
javascriptjqueryhtmlhref

How to pass variable on href?


I am trying to give another variable when href=""

<a href="a.html" id="a">Hello</a>

Above is my code.

I want to pass value apple named fruit variable when going to a.html. How can I do this in JavaScript or jQuery?


Solution

  • The only way that JS can communicate (easily) between URLs is by creating a parameter on your link. For example:

    <a href="a.html?fruit=apple" id="a">Hello</a>
    

    On the receiving page, fetch that parameter data. If you are wanting the data embedded into the link purely via JS, you can append to the HREF using something similar to this by using the jQuery library:

    $("a").attr("href", '?fruit=' + 'apple');