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?
you don't declare variable in html... you can only declare variables in css (kind of) or in javascript ^^ assuming you meant "in javascript": by using 'var', 'let', or 'const' keywords... The <var> tag is used to highlight the variables of computer programs.
Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html. Save this answer.
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With