I'm struggling with some syntax, mostly why the data-attribute
(HTML5) is affecting the text in the way it is.
Please consider this example which does what is expected
<div id="s"></div>
<script>
var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;
</script>
The result is I see 2 lines in HTML due to the \n
. This is expected
The task means I need to change the way we work into
<div id="s" data-txt="this is it\nand done"></div>
<script>
var ele = document.getElementById("s");
var txt = ele.getAttribute("data-txt");
ele.innerText = txt;
</script>
Note we're now using the data attribute of data-txt
. The issue is this renders the text verbatim, meaning I see 1 line: this is it\nand done
https://jsfiddle.net/he4ydvva/
The fact I can't even use replace (ele.getAttribute("data-txt").replace('\n','blah');
) suggests that although I see \n, the computer is reading something different (maybe the charcode value or similar)
Why does this happen and how do I prevent it?
Edit
I have seen How can I insert new line/carriage returns into an element.textContent? but this won't suffice as I need the string to exist within the data-txt and concatenating as "this is " + String.fromCharCode(13) + "
is not valid for HTML5
` in the first case, however since the page has already been drawn in the second example the literal text is used. – Travis J May 19 '16 at 08:29