Reputation:
I recently made a chat on my website, it works pretty good but i just found out that i can send elements there, like divs, anchors etc, how can i make it plain text?
thats how the code looks like
let msgDiv = '<div id="receivedMsgDiv">\n' +
'<div id="rMsgName" class="messageName">\n' +
''+data.val().name+'' +
'</div>\n' +
'<div id="receivedMsg" class="bounce">\n' +
''+data.val().message+'' +
'</div>\n' +
'<div id="rMsgTime">\n' +
''+data.val().time+'' +
'</div>\n' +
'</div>';
let msg = document.getElementById("msgDiv");
msg.innerHTML += msgDiv;
i want a message to be a plain text so i can send eg "Hey friend i found the solution its: <div id="id">something</div>
instead of "Hey friend i found the solution, its: an element any ideas how to fix that?
Upvotes: 0
Views: 334
Reputation: 65825
Instead of using innerHTML
, which causes the HTML parser to parse the string, use textContent
which doesn't.
In the example below, I just made an input
element to use as data
since you didn't share what data
was. I also used template literals to inject the dynamic values into the string.
let data = document.querySelector("input");
let newDiv =
`<div id="receivedMsgDiv">
<div id="rMsgName" class="messageName">${data.value}</div>
<div id="receivedMsg" class="bounce">${data.value}</div>
<div id="rMsgTime">${data.value}</div>
</div>`;
document.getElementById("msgDiv").textContent += newDiv;
<input name="user" value="John Doe">
<div id="msgDiv"></div>
Upvotes: 2