Alexander Shpindler
Alexander Shpindler

Reputation: 951

How to ignore HTML tags in innerHTML attribute?

I'm making a messenger and my messages don't ignore HTML tags because I simply past a text from input in innerHTML of message. My code:

function Message(sender) {
    ...
    this["text"] = "";
    ...
    this.addText = function (text) {
        this["text"] = text;
    };
    ...
};

And here I display it:

...
var chatMessageText = document.createElement("p");
chatMessageText.innerHTML = message["text"];
...

What can I do for ignoring HTML tags in message["text"]?

Upvotes: 1

Views: 3552

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Update Node#innerText property(or Node#textContent property).

chatMessageText.innerText = message["text"];


Check the difference of both here : innerText vs textContent

Refer : Difference between text content vs inner text

Upvotes: 3

Quentin
Quentin

Reputation: 943142

You can't. The point of innerHTML is that you give it HTML and it interprets it as HTML.

You could escape all the special characters, but the easier solution is to not use innerHTML.

var chatMessagePara = document.createElement("p");
var chatMessageText = document.createTextNode(message["text"]);
chatMessagePara.appendChild(chatMessageText)

Upvotes: 1

Related Questions