0

In HTML, I want to define a block of text in the page, and then reuse the text multiple times on the same page. Can I do this using HTML only?

I specifically don't want the duplicated content to live in another file. I want it to be defined in the same page. Like declaring a constant at the top of a code file and reusing it throughout your code.

nkmcalli
  • 1
  • 2
  • Does this answer your question? [Include another HTML file in a HTML file](https://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file) https://css-tricks.com/the-simplest-ways-to-handle-html-includes/ lists some other options too. The way you'd achieve this is to move the text you want duplicated to a separate file, and then include that new file everywhere you want the duplicate text. – WOUNDEDStevenJones Jun 18 '20 at 19:21

2 Answers2

1

You can use JavaScript inside your HTML Document, so you don't need an extra page. Just define the variable inside a <script> tag (best way would be to do it in the header, but it also works in the body) and then access the value of the variable inside another <script> tag in the body like this:

<!DOCTYPE html>
<html>
<head>
    <script>
    var carName = "Volvo";  <!-- defining the variable -->
    </script>
</head>
<body>

   <p id="demo">Hi.</p>

   <script>
       document.getElementById("demo").innerHTML = carName;  <!-- changing the Hi in the <p> tag to Volvo (value of the variable -->
   </script> 

</body>
</html>

Oh boy, that's the first question I was able to answer ^^

Boommeister
  • 1,591
  • 2
  • 15
  • 54
0

You just duplicate your text couple of times in your html code. You should usually use the p tag.

Mahdyar
  • 65
  • 8
  • We want to define the text as a constant, and then reuse it, so that if we have to change it, we only have to change it in one place, and the change gets picked up everywhere. – nkmcalli Jun 18 '20 at 23:09
  • HTML in not programming language; it's a coding language. It doesn't have variables. If you want to declare a constant variable as a string you should use javascript with html. So either use javascript to use variables or use easier and better ways like jquery. I personally don't like javascript because if it's useless syntax. A lot of people use jquery. Also if you want to use a text couple of times you must code it in html file or use javascript or use both frontend and back end with php mysql or asp.net or etc – Mahdyar Jun 19 '20 at 10:22
  • Thanks that's helpful – nkmcalli Jun 19 '20 at 15:39