如何在element.textContent中插入新行或换行符?

98

假设我想动态创建一个新的DOM元素,并用JS字符串文字填充它的textContent/innerText属性。
这个字符串太长了,我想把它分成三个部分:

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

问题是,如果我写

h1.textContent = "...I would like to insert a carriage return here... \n";

它不起作用,可能因为浏览器将 '\n' 视为纯文本并按照此方式显示('\r' 也无效)。

另一方面,我可以更改 h1.innerHTML 而不是 textContent 并编写::

h1.innerHTML = "...I would like to insert a carriage return here...<br />";

这里可以使用<br />,但这样做会替换掉我的h1标签中的所有HTML内容,而不仅仅是文本内容,这不是我想要的结果.

有没有简单的方法来解决我的问题?
我不想创建多个块元素来使文本处于不同的行。


在标题元素中插入换行符的问题是,特别是如果视口很小,您无法确保标题不会在其他位置也换行。 - kennebec
你为什么想要添加换行符?你想看到渲染后的换行还是不想看? - Ciro Santilli OurBigBook.com
14个回答

1

我遇到了这个问题,根据Nelek的答案建议添加了CSS样式后,我成功地使用模板字符串解决了它。我想使用模板字符串是因为我正在从其他元素中提取和显示数据。

var h1 = document.createElement("h1");

//setting this css style solving problem with new line in textContent.  

    h1.setAttribute('style', 'white-space: pre;');

// Using backticks worked for me after adding the css styling

    h1.textContent = `
       Hello, my name is
       ${name.firstName()} ${name.lastName()}.
       Today is
       ${date}.
    `;

document.body.appendChild(h1);

0
以下代码在 FireFox、IE 和 Chrome 上都能正常工作:
var display_out = "This is line 1" + "<br>" + "This is line 2";

document.getElementById("demo").innerHTML = display_out;

0

Nelek在顶部的回答对于多行textContent是一个很好的答案。 只需添加使用模板字面量。使用模板字面量不需要 \r\n。

var h1 = document.createElement("h1");

// setting white-space css property to get new line in textContent
h1.setAttribute('style', 'white-space: pre-line;');

// use template literals `` to add carriage returns directly in script
// new lines in script will be matched with new lines in textContent
h1.textContent = `This is a very long string and I would like to insert a carriage return
moreover, I would like to insert another carriage return
so this text will display in a new line`;

document.body.appendChild(h1);

目前你的回答不够清晰,请[编辑]以添加更多细节,帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0

一种在避免XSS注入的同时实现的方法如下:

function newLines(element, lines, separator = "!newline!") {
    element.textContent = lines.join(separator);
    element.innerHTML = element.innerHTML.replaceAll(separator, "<br>");
}

你可以这样调用它

newLines(h1, ["a", "b", "c", "<script>alert(2)</script>"])

首先的想法是将所有内容放入textContent中,将separator注入到适当的位置,然后用<br>替换separator


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接