How can I create an HTML element using JS and insert a variable into it?
-
Hello, how to create another element with a variable value in an HTML element.
I am doing with innerHTML but can't figure out how to insert the variable.
элемент.innerHTML = '<div>Как воткнуть сюда переменную?</div>'
Maybe you shouldn't use innerHTML, but something else?JavaScript Anonymous, May 30, 2019 -
var myVar = 'Моя переменная';
var element = document.createElement('div');
element.innerHTML = myVar;
or you can modify your code like this
var myVar = 'Моя переменная';
элемент.innerHTML = '<div>' + myVar + '</div>';
Just remember that the variable must be a string.Jace Castaneda -
You just need to escape the variable:
element.innerHTML = '& lt; div & gt;' + peremenaya + '& lt; / div & gt;';
Anonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!