0

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.

10
  • There are no variables in HTML, you have to do it with JavaScript. Commented May 11, 2021 at 1:22
  • @Barmar it is not a free coding service, everyone knows, and no one asked you to code something for anyone, I am a delphi programmer and i just started few months ago webdevelopment i am a beginner and the only project i am on is personnal and when i am stuck i ask, i have done it with JS but i am asking if this can be done with HTML,Sorry for you if you didn't catch the meaning of community website .... Anyway i read the links you posted ... everything is ok i think Commented May 11, 2021 at 1:32
  • "what's the correct script?" How do we answer that without writing the code for you? Commented May 11, 2021 at 1:33
  • In your load event listener, loop through all the anchors and assign to element.href Commented May 11, 2021 at 1:33
  • You could also use a click event listener on all the anchors, which gets the target to link to from JavaScript. Commented May 11, 2021 at 1:35

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.