I am making a simple confirmation alert with vanilla javascript. I want to provide the alert message using a data-confirm
attribute placed in the html (as in the below runnable snippet). But the newline characters I enter into the message text (i.e. the value of the data-confirm
attribute) are displayed literally as "\n" rather than a new line. This issue does not arise when the exact same characters are entered into an alert directly (i.e. not drawn from the value of a data
attribute).
Running this snippet illustrates the issue. The first alert shows the newline properly and the second does not.
confirmationElem = document.querySelector(`[data-confirm]`);
confirmationElem.addEventListener('click', get_confirmation);
function get_confirmation(e) {
confirmationMessage = e.target.getAttribute('data-confirm');
alert(confirmationMessage);
alert("Line one\nLine two");
}
<div data-confirm="Line one\nLine two">click for a message</div>
This SO post does not answer my question: New line in JavaScript alert box ... nor does any other I've found.
There seems to be some issue based on the fact that I am getting the string value for the message from the data
attribute using .getAttribute('data-confirm')
.
Questions:
- Why do the two alerts in the above snippet display newlines differently?
- How can I make an alert that gets the message value from a
data
attribute display newlines properly?