1

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?
Barmar
  • 741,623
  • 53
  • 500
  • 612
Matt
  • 133
  • 1
  • 6
  • 1
    The html attribute is not a string literal. You cannot use a backslash as an escape character in there. – Bergi Jan 26 '23 at 21:01

1 Answers1

3

HTML does not use the backslash as an escape character, that's why it shows up as a literal backslash. Instead, you need either a literal newline, a numeric character reference or a named character entity reference:

function get_confirmation(e) {
  const confirmationMessage = e.target.getAttribute('data-confirm');
  alert(confirmationMessage); 
}
for (const elem of document.querySelectorAll(`[data-confirm]`)) {
  elem.addEventListener('click', get_confirmation);
}
<div data-confirm="Line one\nLine two">message with a backslash</div>

<div data-confirm="Line one
Line two">message with a linebreak</div>

<div data-confirm="Line one&NewLine;Line two">message with &amp;NewLine;</div>

<div data-confirm="Line one&#10;Line two">message with &amp;#10;</div>

<div data-confirm="Line one&#xA;Line two">message with &amp;#xA;</div>
Bergi
  • 630,263
  • 148
  • 957
  • 1,375