Search code examples
javascripthtmlhrefvar

passing var from js to html


I have searched but wasn't able to find what i am looking for. I have one js file that will have multiple href links in it:

var link1="http://somelink.com"
var link2="http://another.com"
var link3="http://morelinks.com"

etc.... will be many variables

In my html file I would like to be able to call one or more of those link into an href.

<a href="link1">my first link</a>
<a href="link3">random link</a>

My question is , how can I pass one or more of these variables over to my html file?

UPDATE: Ok, here is my code with the snippet that Tugca supplied... I know that Im going to be missing something dumb on my part.

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  <title>Local Hotels</title>
  <link rel="stylesheet" href="HotelStyleSheet.css" />
  <script>
    var link1 = "http://firstwebsite.com";
    var link2 = "http://anotherwebsite.com";
    document.getElementById("link_1").href = link1;
    document.getElementById("link_2").href = link2;
  </script>
</head>

<body onload=resizeTo(480,270)>

  <div class="list">
    <div class="hotel"> <a id="link_1">My first link</a>
    </div>

    <div class="list">
      <div class="hotel"><a id="link_2">The second link</a>
      </div>
    </div>

</body>


Solution

  • You can't pass variable form JavaScript to HTML. In normal work-flow, HTML will be rendered before being unaware of JavaScript. But you can modify HTML (or DOM elements). This is why we're using JavaScript.

    var link1 = "http://stackoveflow.com/";
    document.getElementById("link_1").href = link1;
    document.getElementById("link_2").href = 'http://stackoverflow.com/questions';
    <a id="link_1">my first link</a>
    <a id="link_2">random link</a>