I am facing the following problem: I have a HTML document where I want to print basic status/debug/etc messages.
So, the HTML document contains an empty pre-element whose id is out:
<body onload='init () && main();'>
<pre id='out'>
</pre>
</body>
</html>
The init() function assigns the pre element to a variable:
var out_div;
function init() {
out_div = document.getElementById('out')
return 1;
}
Then, in order to print something into the pre-div, I use this function:
function txt_out(txt) {
out_div.innerHTML += "\n" + txt
}
The newline should make sure that each invocation of txt_out is written on its own line. This works as expected in Firefox. IE however doesn't seem to pay attention to the \n. So, is this wrong on IE's part, or am I doing something wrong?
HTML Break Element : If we want to add a new line to the Webpage by JavaScript only, then Adding HTML line break elements to your string can do the work for you. By using the break element in the string, we have to use the innerHTML property to render the string as HTML and not the text.
HTML specifies that a <script> tag inserted with innerHTML should not execute. For that reason, it is recommended that instead of innerHTML you use: Element. SetHTML() to sanitize the text before it is inserted into the DOM.
'innerHTML' Presents a Security Risk The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
Firstly, to get the innerHTML value of any tag, you either need that tag to have its 'id' property or 'name' property set. Then you can respectively use the 'document. getElementById(yourTagIdValue). innerHTML' or 'document.
This is a known problem in Internet Explorer. As a workaround, insert a <br>
element instead of a newline character.
Doing things like element.innerHtml += something;
is usually a bad practice because it makes the browser re-parse the entire contents of the element. As you add more and more data, every time it gets slower and slower. It also invalidates any references/event listeners that other pieces of code might have on its sub-elements.
Better use a div
tag; something like:
<div id='out'></div>
and then append new sub-elements on the fly:
out_div = document.getElementById('out');
// add a new message
new_element = document.createElement('div');
new_element.textContent = "your message here";
new_element.className = "some_class"; // CSS class for changing the appearance
out_div.appendChild(new_element);
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