-2
let word = "kemal"

let test = document.createElement("div");
test.innerText = `lorem la la bla bla "${<strong>word</strong>}"`;
document.querySelector("body").appendChild(test);

I want to make bold font to word variable. But I got an error about it. How can I use HTML elements inside of the template literal?

Justin Grant
  • 44,807
  • 15
  • 124
  • 208
Hasan Tezcan
  • 1,116
  • 1
  • 11
  • 23
  • 2
    um: `\`lorem la la bla bla "${word}"\`` but innerText is not going to output html. – epascarello Nov 03 '20 at 18:53
  • 1
    **Template Literal** expressions are expected to be javascript expressions that can be evaluated. "stuff" is not a javascript expression – Taplar Nov 03 '20 at 18:54
  • Side note; adding markup to the element with `innerText` is most likely going to not be what you want. You want to use `innerHTML` if you want the markup to be evaluated. – Taplar Nov 03 '20 at 18:56

1 Answers1

1

You want to use innerHTML instead of innerText.

test.innerHTML = "lorem la la bla bla <strong>word</strong>";

Example:

let test = document.createElement("div");
test.innerHTML = "lorem la la bla bla <strong>word</strong>";
document.querySelector("body").appendChild(test);

if you want to replace word with a variable:

test.innerHTML = `lorem la la bla bla <strong>${word}</strong>`;

Example:

let word = "Some Word";
let test = document.createElement("div");
test.innerHTML = `lorem la la bla bla <strong>${word}</strong>`;
document.querySelector("body").appendChild(test);
WFarrow47
  • 31
  • 1
  • 1