Directly adding text into innerHTML without using innerText

Is it possible to add string inside innerHTML without having to use innerText?

like this:

var sentence="<b>hello there</b>";

document.querySelector(".container").innerHTML='<span class="thing"></span>';
document.querySelector(".thing").innerText=sentence;
<!DOCTYPE html>
<html>

  <head></head>

  <body>
  <div class="container"></div>
 
  </body>

</html>

but without having to use innerText,
Maybe the code would look something like this:
var sentence="<b>hello there</b>";

document.querySelector(".container").innerHTML='<span class="thing">'+raw(sentence)+'</span>';

Answer

I don’t see anything seriously wrong with your current approach. If you want to avoid the repetition of creating an element with a particular class and then have to select it again right after you append it, you can consider creating an element instead of an HTML string:

var sentence="<b>hello there</b>";

document.querySelector(".container")
  .appendChild(document.createElement('span'))
  .textContent = sentence;
<div class="container"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *