Declare a Variable and Use It in Html [Duplicate]

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 =  
var imagesrc =  
</script>

HTML Part:

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

What is the correct syntax/way to do it?

2

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 = ""
    var img = document.getElementById('dynamicImg'); 
    img.src = ""
  </script>
</html>
2
const imagehref = ""; 
const imagesrc = ""; 

function update(className, property, value) {
  Array.from(document.getElementsByClassName(className)).forEach(elem => (elem[property] = value)) 
}

update("imagehref", "href", imagehref)
update("imagesrc", "src", imagesrc)
<a class="imagehref"><img class="imagesrc" /> </a>
<a class="imagehref"><img class="imagesrc" /> </a>
<a class="imagehref"><img class="imagesrc" /> </a>

Add an identifier to the anchor tag, then use setAttribute to set the href and src

var imagehref = '
var imagesrc = '

let anchor = document.getElementById('test');
anchor.setAttribute('href', imagehref);
anchor.querySelector('img').setAttribute('src', imagesrc)
<a id='test' href=''><img src='' /></a>
Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest