1

I have a Tampermonkey script that creates a list of values from checked checkboxes on a webpage. The box displays the data beautifully, each value on a new line below the other. However, I lose the newline characters when I copy and paste these values using Microsoft clipboard. Is there a way to adjust the script in order to allow preservation of the newline characters (\n)?

JavaScript:

var box = document.createElement( 'div' );
box.id = 'myAlertBox';

document.body.appendChild( box );

box.textContent = text + '\n';

var selectedQueries = document.querySelectorAll (query);

selectedQueries.forEach ( (chkBox) => {
    box.textContent += chkBox.title + '\n';
});

CSS:

#myAlertBox {
    font-size: small;
    background: white;
    border: 5px solid green;
    padding: 4px;
    position: absolute;
    top: 280px; right: 80px;
    max-width: 300px;
    white-space:pre-wrap;
}
JG7
  • 371
  • 2
  • 10
  • Newlines in windows are `\r\n`, so... you might find your answer in here https://stackoverflow.com/questions/1155678/javascript-string-newline-character if so we can close as dupe. –  Sep 21 '17 at 15:06
  • Possible duplicate of [How do I replace all line breaks in a string with
    tags?](https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags)
    – Terry Sep 21 '17 at 15:09
  • That is because `\n` is a line-break character, but remember that in HTML all whitespaces are treated as collapsible space (unless you set `white-space: pre`). If you want a line break in HTML, you will have to convert it to `
    `. This can be done using regular expression.
    – Terry Sep 21 '17 at 15:09
  • The data is added as text content. Do I need to change from a text box to HTML content instead? – JG7 Sep 21 '17 at 15:15

2 Answers2

1

Thanks everyone! I simply changed textContent to innerHTML and used <br/> as the line breaks as suggested. You have all collectively saved me a lot of manual labor.

Working code:

function ParseCheckBoxes (query, text) {

    if (document.getElementById('myAlertBox') !== null) {
        document.getElementById("myAlertBox").outerHTML='';
    }

    var box = document.createElement( 'div' );
    box.id = 'myAlertBox';

    document.body.appendChild( box );

    box.innerHTML = text + '<br/>';

    var selectedQueries = document.querySelectorAll (query);

    selectedQueries.forEach ( (chkBox) => {
        box.innerHTML += chkBox.title + '<br/>';
    });
}
JG7
  • 371
  • 2
  • 10
0

HTML will not support \n because it will treated as white space. Use <br/> tag for line break.

var box = document.createElement( 'div' );
box.id = 'myAlertBox';

document.body.appendChild( box );

box.textContent = text + '<br/>';

var selectedQueries = document.querySelectorAll (query);

selectedQueries.forEach ( (chkBox) => {
    box.textContent += chkBox.title + '<br/>';
});