简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM