简体   繁体   English

如何设置元素的 textContent,而不修剪字符串?

[英]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.

相关问题 Javascript - 获取元素的格式化文本内容? - Javascript - Getting formatted textContent of an element? 如何使用 .textContent 更新元素 - How to update an element using .textContent JS textcontent 仅设置为字符串的一部分 - JS textcontent set as only part of a string 在Facebook的聊天中设置或替换textContent - Set or replace textContent in Facebook's chat 如何在不更改其 textContent 值的情况下将字符附加到 SVG 文本元素? - How to append characters to an SVG text element without changing its textContent value? 如何在不创建HtmlElement的情况下从HTML字符串中提取textContent? - How can I extract the textContent from an HTML string without creating a HtmlElement? 如何在 textContent 中包含图像的替代文本? - How to include image's alternative text with textContent? 获取单击的下拉元素的 textContent 的标准方法不起作用 - Standard way of getting textContent of clicked dropdown element not working 尝试在HTML错误上使用textContent时遇到错误。 “无法设置未定义的属性&#39;textContent&#39;” - Getting error trying use textContent on an HTML error. “Unable to set property 'textContent' of undefined” JS-如何获取outerHTML textContent的字符串? - JS - how to get a string of outerHTML textContent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM