I wanted to capture the user's text-input in a variable USER_INPUT and use the value of that variable as a substring of a multi-styled string that is shown in some DISPLAY div. But there were problems with text-inputs containing html tags, like <div>, as in the following example, where the value of USER_INPUT does not appear at all in DISPLAY, which is understandable, due to the different nature of the .innerText and .innerHTML properties.
var USER_INPUT = "<div>";
document.getElementById("DISPLAY").innerHTML =
"<span style='color:red'>" + "User Input : " + "</span>" +
"<span style='color:blue'>" + USER_INPUT + "</span>";
So after much experimentation, a solution appeared which seems to work well in all cases:
var USER_INPUT = "<div>";
var XDIV = document.createElement("div");
XDIV.innerText = USER_INPUT;
var A = XDIV.innerHTML;
document.getElementById("DISPLAY").innerHTML =
"<span style='color:red'>" + "User Input : " + "</span>" +
"<span style='color:blue'>" + A + "</span>";
The above code shows in the DISPLAY:
which is exactly what I need, that is, to be able to style the user-input independently of the first part of the string.
My problem is that I cannot understand why the above code solves the problem. If the user-input string is passed in a new div as innerText and retrieved as innerHTML, then it miraculously appears correctly in the DISPLAY. I would like to understand the rationale behind this behavior, so any help would be greatly appreciated. fiddle here
Property innerHTML returns or accepts a serialized HTML or XML.
document.getElementById("my-id").innerHTML = "<p>Foo <strong>bar</strong> baz.</p>"
will display "Foo bar baz." as a text.
If you want to display HTML tags you need to escape < to < and > to > to get <p>Foo <strong>bar</strong> baz.</p>
You can use this function to do it (taken from this answer):
function escapeHTML(html) {
return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With