Reputation: 53
Unable to show "\t" on the web page when it has been inserted using javascript into div.
Take a look at below code snippet. The first div shows "\t" as text but when they are inserted into div using javascript, they get rendered by the browser and not displaying it as text on UI.
I need to insert text in div using javascript, the text contains "\t" character and I need to show them as it is, without rendering it.
I looked at many similar questions on stackoverflow, but none of them really worked. Please advise.
function callme() {
document.getElementById('div2').innerHTML = "I am div 2, tab char 1:\t , tab char 2: \t";
}
<!DOCTYPE html>
<html>
<body>
<span id='div1'>I am div 1, tab char 1: \t , tab char 2: \t</span>
<br /> <br /> <br />
<button onclick="callme()">Click me to Insert tab characters in below div</button>
<br /> <br />
<span id='div2'>I am div 2, click above button insert tab characters</span>
</body>
</html>
Upvotes: 1
Views: 1922
Reputation: 65806
Just escape the \
character with \\
.
By the way (FYI):
Don't bother with self-terminating tags (<br />
). They gain you nothing and can lead to bugs in the code. You can read more about that here.
<br>
shouldn't be used to insert blank space into the layout of a document. It should only be used to place part of some content on to the next line. All layout should be handled by CSS.
Don't use inline HTML event attributes (onclick
) as there are many reasons not to use this 25+ year old technique that just will not die the death it deserved. Instead, follow the modern, standards-based element.addEventListener()
API.
let output = document.getElementById('div2');
document.querySelector("button").addEventListener("click", callme);
function callme() {
output.innerHTML = "I am div 2, tab char 1:\\t , tab char 2: \\t";
}
/* All layout should be done with CSS */
div { margin:2em 0; }
<div id='div1'>I am div 1, tab char 1: \t , tab char 2: \t</div>
<button>Click me to Insert tab characters in below div</button>
<div id='div2'>I am div 2, click above button insert tab characters</div>
Upvotes: 1
Reputation: 1191
Add one more \
to escape the \ character.
Also, you can use pre tag for that purpose.
Here is the Solution.
function callme() {
document.getElementById('div2').innerHTML = "I am div 2, tab char 1:\\t , tab char 2: \\t";
}
<!DOCTYPE html>
<html>
<body>
<span id='div1'>I am div 1, tab char 1: \t , tab char 2: \t</span>
<br /> <br /> <br />
<button onclick="callme()">Click me to Insert tab characters in below div</button>
<br /> <br />
<span id='div2'>I am div 2, click above button insert tab characters</span>
</body>
</html>
Upvotes: 0