# Using Variables in HTML Markup - JavaScript

**URL:** <https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826>\
**Category:** Uncategorized\
**Created:** [January 25, 2021, 11:11pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826 "2021-01-25T23:11:09Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![georgetown23](https://avatars.discourse-cdn.com/v4/letter/g/7ab992/32.png) [@georgetown23](https://forum.kirupa.com/u/georgetown23)\
**Post date:** [January 25, 2021, 11:11pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/1 "2021-01-25T23:11:09Z")

</div>

Hi All,

Is there a way to use a JavaScript Variable inside of a HTML file? Do I need to use another library? Basically, I want to make it easy for for someone who doesn’t know HTML to edit all the urls in one place.

(screenshot of code below)

Thanks in Advance!

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [January 25, 2021, 11:13pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/2 "2021-01-25T23:13:41Z")

</div>

If you put variables in a `<script>` tag, they can be right there in the HTML. Those variables will be global and will be accessible from any other JavaScript running in the page. This will let you have variables that can be easily exposed and editable from anyone with access to edit the HTML without them having to dig through other code).

---

<div class="post-metadata">

**Author:** ![georgetown23](https://avatars.discourse-cdn.com/v4/letter/g/7ab992/32.png) [@georgetown23](https://forum.kirupa.com/u/georgetown23)\
**Post date:** [January 25, 2021, 11:16pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/3 "2021-01-25T23:16:27Z")

</div>

![snippet](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/2X/0/032edc150e0dd3809650390d6989f7e0fc309f76.jpeg)

Thank you. Here’s is what I’m trying to do. Somehow it wasn’t included in my original post.

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [January 25, 2021, 11:54pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/4 "2021-01-25T23:54:20Z")

</div>

Ah, yeah that’s a little different. HTML itself doesn’t support anything like this. Usually that’s handled by some other framework or templating engine.

You could create a script a the end of your HTML to go through and make the replacements after the HTML is parsed. But you have to be careful with things like `src` attributes because the browser will throw a lot of errors with bad requests when it tries to load the url “{{imgSrc1}}” and can’t find it.

To get around this you could put the properties in a data attribute and then have your script move them to the original when making the replacements

```
<script>
var imgSrc1 = "https://placehold.co/300x300";
var imgSrc2 = "https://placehold.co/200x200";
var imgSrc3 = "https://placehold.co/100x100";
</script>

<img data-src="imgSrc1" />
<img data-src="imgSrc2" />
<img data-src="imgSrc3" />

<script>
// make replacements for data attributes
for (let img of document.querySelectorAll('img[data-src]')) {
	img.src = window[img.dataset.src]
}
</script>

```

This is a very simple implementation that specifically targets images with a src property. You may need to get more involved depending on where and how you want to use variables like this.

---

<div class="post-metadata">

**Author:** ![krilnon](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/krilnon/32/34_2.png) [@krilnon](https://forum.kirupa.com/u/krilnon)\
**Post date:** [January 25, 2021, 11:59pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/5 "2021-01-25T23:59:39Z")

</div>

Senocular’s advice is the advice you should take, but I couldn’t resist:

```auto
<!doctype html>
<html>
  <head>
    <meta charset=utf-8">
    <script type="text/javascript">
    let imageSource1 = 'image1.jpg'
    let imageSource2 = 'image2.jpg'
    let imageSource3 = 'image3.jpg'
    let imageSource4 = 'image4.jpg'
    let imageSource5 = 'image5.jpg'

    let _ = (_, src, self) => {
      self.setAttribute('src', src)
      self.setAttribute('onerror', '')
    }
    </script>
  </head>
  <body>
    <div>
      <img src onerror="_`${imageSource1} ${this}`" />
      <img src onerror="_`${imageSource2} ${this}`" />
      <img src onerror="_`${imageSource3} ${this}`" />
      <img src onerror="_`${imageSource4} ${this}`" />
      <img src onerror="_`${imageSource5} ${this}`" />
    </div>
  </body>
</html>

```

Edit: Improved to match my original vision a bit more. Quite close to `{{ imageName }}`!!

---

<div class="post-metadata">

**Author:** ![georgetown23](https://avatars.discourse-cdn.com/v4/letter/g/7ab992/32.png) [@georgetown23](https://forum.kirupa.com/u/georgetown23)\
**Post date:** [January 26, 2021, 5:47pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/6 "2021-01-26T17:47:20Z")

</div>

> [@krilnon](#):
>
> ```auto
> let imageSource2 = 'image2.jpg'
> let imageSource3 = '
> 
> ```

Thank you for the help! I ended up doing it a little differently but it works:

 ![image](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/2X/e/e5081ef894730812518d3f4cbe202afd43d293dd.png)

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [January 27, 2021, 4:07am UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/7 "2021-01-27T04:07:18Z")

</div>

One thing to keep in mind about `document.write` is that it will clear out everything in your page. The approaches **sen** and **kril** outlined above will allow you to keep your page content while also having images whose paths are defined in HTML 🤖

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [January 27, 2021, 2:51pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/8 "2021-01-27T14:51:29Z")

</div>

> [@kirupa](#):
>
> One thing to keep in mind about `document.write` is that it will clear out everything in your page.

It will do this only if called after the page is finished parsing. In georgetown23’s example, it will work as expected, retaining the rest of the page’s contents.

That said, for this reason, and others, generally you’ll want to steer clear of document.write.

---

<div class="post-metadata">

**Author:** ![georgetown23](https://avatars.discourse-cdn.com/v4/letter/g/7ab992/32.png) [@georgetown23](https://forum.kirupa.com/u/georgetown23)\
**Post date:** [January 27, 2021, 3:36pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/9 "2021-01-27T15:36:25Z")

</div>

Hello All! I did a bit more research and believe using **Template Literals** is a better/modern way to do it? (BTW- how do we add actual code here?)

 ![image](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/2X/2/28674120dc79e28c7ad2e7854a421f8fb9506588.png)

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [January 27, 2021, 5:47pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/10 "2021-01-27T17:47:42Z")

</div>

> [@georgetown23](#):
>
> Hello All! I did a bit more research and believe using **Template Literals** is a better/modern way to do it?

If you’re talking about JavaScript code, then yes. Template literals allow you to add substitutions directly in JavaScript string literals when using back ticks (```). But now you’re writing HTML in JavaScript which can get confusing.

Given:

> [@georgetown23](#):
>
> Basically, I want to make it easy for for someone who doesn’t know HTML to edit all the urls in one place.

it sounded like you wanted to keep things simple for people who don’t know HTML very well. And if they wanted to edit an `<img>` tag, having that inside the JavaScript code could make that difficult.

Now if this “someone” is _only_ interested in the variables and nothing else, then it doesn’t really matter. You can take any number of approaches to convert the variables into image paths. I think that’s up to you and whatever you feel comfortable with.

I, personally, like keeping everything together to help prevent surprises. For example, upon seeing

```
<div id="content"></div>

```

I’m immediately going to think, “Oh nice, an empty div. How uninteresting!” Little do I know that div is going to get populated with image elements after some script later down the road eventually runs.

With my previous example there’s image tags where there’s going to be image tags, and with a little guessing you can probably equate `data-src` attributes to `src` attributes thanks to a little hidden magic somewhere, but at least you know the images are there.

> [@georgetown23](#):
>
> (BTW- how do we add actual code here?)

Once you add code, you can select it and click on the code icon in the editor: ![image](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/2X/7/7d66bf84d35f23ea9336027b215c61923f6b912e.png)

You can also format code manually by using a single back tick for inline code ``such as this``. Or for block code indenting by 4 spaces

```plaintext
    such
    as
    this

```

For block code, you can also use 3 back ticks along with an optional language to help with color coding. If you don’t specify a language one will be inferred.

````
```
like
this
```

````

or

````
```javascript
like
this
```

````

The code icon will default to 4 spaces for multiline code, but if you want more control over formatting you might want to force it with 3 back ticks.

… and yes, having the code as text in posts is better than screenshots 😉

---

<div class="post-metadata">

**Author:** ![georgetown23](https://avatars.discourse-cdn.com/v4/letter/g/7ab992/32.png) [@georgetown23](https://forum.kirupa.com/u/georgetown23)\
**Post date:** [January 28, 2021, 3:45pm UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/11 "2021-01-28T15:45:39Z")

</div>

Thank you for the detailed response! Makes sense that they shouldn’t have too look elsewhere for the code. I’ll keep optimizing but I’m all set here. 😀

---

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [January 30, 2021, 6:56am UTC](https://forum.kirupa.com/t/using-variables-in-html-markup-javascript/645826/12 "2021-01-30T06:56:19Z")

</div>

Hi George,  
The easiest way to achieve that is to set the url in a css variable on the object  
eg. \<div id = ‘one’ class = ‘image’ style = '- -imgSrc: '‘www.eg one";’ \>.\<div id = ‘two’ class = ‘image’ style = '- -imgSrc: '‘www.eg two";’ \>.  
Then set the background image as the url in your CSS.  
e.g. .image{ background-image: var(- -imgSrc);}  
The CSS will then block scope the variable to the element because it is inline and display the correct image for each div despite having the exact same variable name.  
This is super handy for complex animations because you can change a class on a parent element and the children update with their different variables, you can also run a single animation and have different effects on different elements.  
(I have only used this for animations but I seen no reason why it wouldn’t work for urls)  
Good luck,  
P.S- misunderstood what you where trying to do (I’m fragged, disregard 😁)
