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...
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?
3 Answers
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>
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>