It is necessary to make sure that in the HTML code (in the text of the page itself) certain values ​​of variables appear, which are calculated in the .js file, now I do it like this:

let variable = 123; document.getElementById('variable').innerHTML = variable; <p>Текст в HTML: <span id = variable></span></p> 

But it seems to me to be somehow a crutch, since with a large number of variables, the code in js looks very cumbersome, besides, the id value should be unique, so I cannot use the same variable more than 1 time

Tell me the solution

  • one
    This is not a crutch ... they do that too. But usually the information is kept in the data-[название] attributes - Vitaly Shebanits

1 answer 1

The question is where exactly the variables come from and where exactly should they be displayed in HTML. If variables can be packaged into an array, then all values ​​can be output, for example, in a loop, dynamically creating spans and filling them with values:

 const vars = [123, 456, 789, 101112, 131415, 161718]; const p = document.getElementById('from-js'); for(let i = 0; i < vars.length; i++) { const span = document.createElement('span'); p.appendChild(span).textContent = vars[i]; } 
 span { display: inline-block; border: 1px solid red; padding: 5px; margin: 5px; } 
 <p id="from-js"></p>