首页 > 解决方案 > Can't set innerHTML when using strings that start with '<'

问题描述

I have a textarea that will populate another section with what the user inputs and my code works fine as long as I dont type anything starting with "<". Whenever I have a string like "<anything else can follow" that starts with "<", it wont set the innerhtml.

var text = "<i wont print"
text = "i will print!"
trans_txt.innerHTML = text;

Is "<" some kind of override character for innerhtml? I was wondering if anyone knew what was happening and if there is a way I could change the text var into purely string without having to worry about my string not showing up.

edit: I realized this because the default textarea message is "<text area"

标签: javascripthtmlcss

解决方案


<i followed by a space is HTML syntax for "Start an <i> (idiomatic/italic) tag" Since the parser doesn't see the end of the tag's definition (that is, a >), everything between the <i and the end is considered an error and dropped.

If you want to insert plain text only, use textContent instead:

var text = "<i wont print"
document.body.textContent = text;

textContent is also faster and safer. Only use innerHTML when deliberately inserting HTML markup.

Don't use innerText - best to prefer textContent instead in almost all situations.


推荐阅读