jQuery append is not parsing HTML tags

Viewed 228

It seems like many people have had this problem in the past but none of the solutions work for me.

I have a method that is firing after receiving a response from a POST request:

        xhr.onload=function(e) {
                if(this.readyState === 4) {
            res = JSON.parse(e.target.responseText);

            var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>";
            document.getElementById("chatbox").append(userHtml);

            var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>";
            document.getElementById("chatbox").append(botHtml);

            document
              .getElementById("userInput")
              .scrollIntoView({ block: "start", behavior: "smooth" });
                }
        };

Inside a "chat bot", this is supposed to render a text bubble on the right (for the userText) and a text bubble on the left (for the botText). However, when this method triggers, it just appends the raw HTML into the chatbox, as so:

<p class="userText"><span>Hi, how are you.</span></p><p class="botText"><span>I'm fine thanks, how are you?</span></p>

Is there a way I can fix this?

Thanks!

1 Answers

You need to use jQuery / append() function not document.getElementById

I have added both methods below and you can see that $('#chatbox') is parsing the HTML while document.getElementById is displaying out as a plain HTML / (raw) text

Live Demo:

var res = {
  userText: 'bar',
  botText: 'foo'
}

var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>";
document.getElementById("chatbox").append(userHtml);
$('#chatbox').append(userHtml)

var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>";
document.getElementById("chatbox").append(botHtml);
$('#chatbox').append(botHtml)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chatbox">

</div>

Using document.getElementById

If you are keen on using document.getElementById then you need to use innerHTML like this below.

Live Demo:

var res = {
  userText: 'bar',
  botText: 'foo'
}


var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>";
document.getElementById("chatbox").innerHTML += userHtml;

var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>";
document.getElementById("chatbox").innerHTML += botHtml;
<div id="chatbox">

</div>

Related