0

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>';
3
  • 2
    It's possible, but not a very good idea IMO. Your first approach is perfect, I thnk (except - use .textContent instead of the less-standard and weird .innerText) Commented Mar 6, 2021 at 22:34
  • @CertainPerformance innerText is a very useful property when it comes to preserving white-space and newlines. As such, the only "weird" thing about it is that it was never standardized. Commented Mar 6, 2021 at 22:40
  • 2
    @connexo He said he was thinking of something like raw(sentence) so I thought he meant he wanted to see the plain text as a result, not the HTML markup. @lemonface, is your first snippet producing the output you want? Commented Mar 6, 2021 at 22:44

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

I'm assuming OP expects bold text to show up.
If your interpretation is correct, you can also use document.querySelector(".container") .appendChild(document.createElement('span')).appendChild(document.createTextNode(sentence)).
@CertainPerformance thank you! This is exactly what I was looking for! Just for a reference to the future travelers who might stumble upon this Q, you can first create a temp element and add style and/or class to it like this jsfiddle.net/t93v7sa8/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.