I’m trying to incrementally add letters to a HTMLElement
, but whitespace (most spaces, some linebreaks) seem to disappear when I do this
For example:
let s = "f o o b a r";
let e = document.createElement('span');
for (let i = 0; i < s.length; i++) {
// do some stuff
e.innerText += s[i];
}
// e.innerText = "foobar"
I’ve stepped through the code and seen e.innerText += " "
when s[i] = " "
, but I can’t figure out why it doesn’t get added to e
. My assumption is somehow the whitespace gets trimmed due to it being the last item, but I’m unsure how to stop this (short of setting whitespace: pre
, but that also prevents linebreaks and seems overkill)
3
Answers
This is probably an HTML issue rather than a JavaScript issue. In HTML, whitespace in the source is collapsed to only display one space on the page. It was designed this way so that when HTML page authors could insert as many line breaks or indentation as they wanted for organisation without affecting the display.
In your case, since you want the white space to display, there are a few choices for how to work around this:
white-space: pre-wrap
which preserves spaces while still allowing text to flow across lines.innerText
property is "aware of the rendered appearance of the text", the value of the property in JavaScript will reflect how spaces are treated in the DOM. So if whitespaces are collapsed, they will also be removed from the value ofinnerText
. You can avoid this by using the standardtextContent
property instead.To learn more, you can read more about the fundamentals of whitespace collapsing on MDN here.
If this doesn’t answer your question, I recommend you add a screenshot of what you expected vs what you got to your original question to help people provide more accurate answers.
you can use t.textContent += s[i];
InnerText represents only the visible text content of an element and does not include any whitespace or HTML tags.
The string is an array of characters. You can access every element by index. You can do it by following: