Search code examples
javascripthtmlvariablesvar

Declare a variable in javascript and use it in html


I have big html document with various images with href and src.

I want to declare their href and src so as to change only their var values. something like...

<script>
var imagehref = www.url.com; 
var imagesrc = www.url.com/img.pg; 
</script>

HTML Part:

<html>
<a href=imagehref><img src=imagesrc /> </a>
</html>

What is the correct syntax/way to do it?


Solution

  • You can't do it in this way, you have to set href and src directly from the js script. Here's an example:

    <html>
      <body>
        <a id="dynamicLink" href=""><img id="dynamicImg" src="" /> </a>
      </body>
      <script>
        var link = document.getElementById('dynamicLink'); 
        link.href = "http://www.url.com"
        var img = document.getElementById('dynamicImg'); 
        img.src = "http://www.url.com/img.png"
      </script>
    </html>