cak3_lover
cak3_lover

Reputation: 1958

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>';

Upvotes: 0

Views: 216

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371069

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>

Upvotes: 2

Related Questions