8

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?

2
  • so as to change only their var values Even if you do, changing value of a variable will not change src of image Commented Mar 12, 2019 at 14:23
  • If you want to change image with a variable, check that out Commented Mar 12, 2019 at 14:24

3 Answers 3

10

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>

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

2 Comments

Worked. And extending it for multiple images...
<body> <a id="movieLink1" href=""><img id="movieImg1" src="" /> </a> <a id="movieLink2" href=""><img id="movieImg2" src="" /> </a> <script> var link = document.getElementById('movieLink1'); link.href = "href1" var img = document.getElementById('movieImg1'); img.src = "imgsrc1" var link = document.getElementById('movieLink2'); link.href = "href2" var img = document.getElementById('movieImg2'); img.src = "imgsrc2" </script> </body>
1

const imagehref = "https://google.com"; 
const imagesrc = "https://media3.giphy.com/media/sIIhZliB2McAo/giphy.gif"; 

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>

Comments

0

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

var imagehref = 'www.url.com';
var imagesrc = 'www.url.com/img.pg';

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.