Search code examples
javascriptvariablesdynamichref

Link HREF dynamic variable


Having several links in my webpage with the same HREF value, this value will change on a daily basis, i don't want to change all values of links (easily 20). My question is : is there a way to store the value in one variable in the HTML code and make all links take theirs HREFs from this value ? I know it can be done in javascript so whats the correct script and do i have to put it in the onload event ? below the script i use to change all links with the variable;

<span style="display:none" id="dynamiclink" data-alink="http://www.google.com"></span>
<a href="#" id="link1">Link 1</a>
<a href="#" id="link2">Link 2</a>
<a href="#" id="link3">Link 3</a>

<script>
const spanlink = document.getElementById("dynamiclink");
const dynlink= spanlink.getAttribute("data-alink");
document.getElementById("link1").setAttribute("href",dynlink);
document.getElementById("link2").setAttribute("href",dynlink);
document.getElementById("link3").setAttribute("href",dynlink);
</script>

Edited, here is my code, so to be more clear my question was can i do this with HTML, i mean is there a way in HTML to link element attribute as HREF to a variable,

Thanks again guys.


Solution

  • Give all the links the same class and use a loop to set them all.

    const spanlink = document.getElementById("dynamiclink");
    const dynlink= spanlink.getAttribute("data-alink");
    document.querySelector(".alink").forEach(link => link.href = dynlink);
    <span style="display:none" id="dynamiclink" data-alink="http://www.google.com"></span>
    <a href="#" class="alink">Link 1</a>
    <a href="#" class="alink">Link 2</a>
    <a href="#" class="alink">Link 3</a>