is it possible to assign the textContent of an element to be HTML code in JS?

时间:2019-02-24 03:09:10

标签: javascript html css

I know you can use backticks to do this regularly, but are you able to concatenate those backticks?

For example, will

let bar = 42;
let foo = document.createElement("div");
foo.innerHTML = `<div> this number is ` + bar + ` </div>`;

be..

<div> this number is 42 </div>

If not, is there another way to do this? I am trying to create create elements with textContent that is only in my JS file

1 个答案:

答案 0 :(得分:1)

Backticks are meant to make it easier for you to combine strings. For example,

`This is a variable: ${testVariable}`;

is the same thing as

"This is a variable: " + testVariable;

In your case, both will result in a string, so you would be able to use both of them to create elements.