0

Is it possible to define string variables at the top of the page and then reference them in my HTML code? If so, how would I do this?

Here's an example of the code (how i assume it may look):

<script>
    var title = "Title"
    var desc = "Description"
</script>

<h1> title variable here </h1>
<p> desc variable here </p>
Trent
  • 13
  • 1

3 Answers3

0

You can't access JS variables in HTML. You need to make changes to the document within JavaScript.

document.querySelector("h1").innerHTML = title;

This code looks for the first <h1> element in your document and sets everything within the element to the variable title. Take a look at the JS Tutorial by W3 Schools.

nilsf
  • 118
  • 1
  • 10
0

A bit of a hack, but you could grab the innerHTML and replace template variables e.g. surrounded by double-curly braces.

I recommend avoiding this, and instead use a templating library such as handlebars

const
  title = 'Title',
  desc = 'Description',
  substitute = (text, replacements) =>
    text.replace(/\{\{(\w+)\}\}/g, (g0, g1) => replacements[g1]),
  substituteHtml = (el, replacements) =>
    el.innerHTML = substitute(el.innerHTML, replacements);

substituteHtml(document.body, { title, desc });
<h1>{{title}}</h1>
<p>{{desc}}</p>

A better alternative

Example templating library usage using handlebars. This let's us build/modify HTML content safely.

const
  context = {
    title: 'Title',
    desc: 'Description'
  },
  template = document.querySelector('#handlebars-demo').innerHTML,
  templateFn = Handlebars.compile(template);

document.querySelector('.output').innerHTML = templateFn(context);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<div class="output"></div>
<script id="handlebars-demo" type="text/x-handlebars-template">
  <h1>{{title}}</h1>
  <p>{{desc}}</p>
</script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
-1

Only with JavaScript when the page loads, like this...

<body onload="T.innerHTML=title; D.innerHTML=desc;">
  <script type="text/javascript">
    var title = "Title",
      desc = "Description";
  </script>
  <h1 id="T"></h1>
  <p id="D"></p>
</body>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
SomeUser
  • 1
  • 1
  • 2
    Avoid using `window.T` as a replacement for `document.findElementById('T')`. It is bad practice and is not guaranteed to work in modern browsers. It was introduced by IE and was never adopted officially by ECMA. – Mr. Polywhirl Apr 21 '21 at 18:08
  • Sorry I don't agree with that. I'm a browser author thanks. – SomeUser Apr 21 '21 at 18:13
  • Please see: [_"Do DOM tree elements with ids become global variables?"_](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) – Mr. Polywhirl Apr 22 '21 at 16:21
  • Also inline onload is not recommended. Use window.addEventListener – mplungjan Apr 22 '21 at 20:13