[英]How to set an element's textContent, without the string getting trimmed?
I'm trying to set an element's text content (a div
element) to something the user has given as input.我正在尝试将元素的文本内容( div
元素)设置为用户作为输入提供的内容。 I don't really want to use element.innerHTML = (...)
because then it could be parsed as HTML code instead of plain text, so I'm using element.textContent = (...)
.我真的不想使用element.innerHTML = (...)
因为那样它可以被解析为 HTML 代码而不是纯文本,所以我使用element.textContent = (...)
。
However, there can be spaces at the beginning (and at the end) of the input string, and I don't want the string to be trimmed before inserted into the element.但是,输入字符串的开头(和结尾)可能有空格,我不希望在插入元素之前对字符串进行修剪。
With innerHTML
, I could simply replace all spaces with
使用innerHTML
,我可以简单地用
替换所有空格
, but textContent
doesn't show that as a space, but as plain
,但textContent
并没有将其显示为空格,而是将其显示为简单的
. .
How can I do it?我该怎么做? Thanks in advance :)提前致谢 :)
To make whitespace render as it exists in the DOM, you can apply white-space: pre-wrap
in CSS:要使空白在 DOM 中呈现,您可以在 CSS 中应用white-space: pre-wrap
:
for (const target of document.getElementsByClassName('target')) { target.textContent = " Some text with various spaces "; }
.preserve-whitespace { white-space: pre-wrap; } .target { border: 1px solid red; float: left; clear: left; margin-top: 0.5em; }
<div class="target"></div> <div class="target preserve-whitespace"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.