So I’m having a problem where my code doesn’t want to break line even after I put the correct syntax
oldchat = ''
var paragraph = document.getElementById("chat");
function SendMsg() {
let x = document.getElementById("Username")
let username = x.value
let message = prompt();
chat = (oldchat + "n" + username + ": " + message)
oldchat = chat;
let Modifiedmessage = document.createTextNode("n" + username + ":" + message)
paragraph.appendChild(Modifiedmessage);
}
<input id="Username">
<button onclick="SetUser()">Set Username</button>
<button onclick="SendMsg()">send message</button>
<br>
<div id="chat">
</div>
I was expecting my code to break line have it be like
VibingCat: Hi
User123: Hello there!
4
Answers
n is not a line break in HTML, but <br> Is.
Also you don’t need to create a new text node for the modified message in the SendMsg() function, as you are already adding HTML to the paragraph element.
EDIT: As @Roko C. Buljan innerHTML will make you vulnerable to XSS attacks so don’t use it.
I’m keeping the answer in case someone had the same idea.
You need to use html tags instead of "n" when you are rendering chat inside the div element, therefore you need to send DOM elements to be rendered inside that div element.
should be
Hi This is new version of the code
line-break: pre-wrap;
in order to interpret then
textContent
instead ofinnerHTML
, or create text nodes instead of HTML.As you see from the above:
const
where neededprompt()
use<textarea>
insteadon*
handlers, useaddEventListener()
instead. JS is supposed to be in one place, and that’s the respective file or tagtrim()
your messages from whitespaces