Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = 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?

like image 241
vasilis smyrnios Avatar asked Mar 12 '19 14:03

vasilis smyrnios


People also ask

Can you declare a variable in HTML?

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.

How do I declare a new variable in HTML?

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.

How do you put a variable in a script in HTML?

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.

Can we declare a variable twice?

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.


2 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 = "http://www.url.com"
    var img = document.getElementById('dynamicImg'); 
    img.src = "http://www.url.com/img.png"
  </script>
</html>
like image 140
Luca Pierfederici Avatar answered Oct 13 '22 00:10

Luca Pierfederici


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>
like image 21
AlexOwl Avatar answered Oct 13 '22 00:10

AlexOwl