字符串包括 tags rendering as HTML content instead of string in DOM query

问题描述 投票:0回答:2

我有一系列字符串,其中一些格式像<p>Text here</p>,其他格式如“文字在这里”。我遇到的困境是我希望字符串呈现并实际包含字符串<p>Text here</p>中的p标记。但是,这会导致文本被包装在html段落标记中。

基本上,我使用document.getElementById("stringLocation").innerHtml = " <p>Text here</p>"分配字符串

如何成功使用这些DOM元素分配给dom并将<p>标记包含在字符串中,而不是html的一部分?

javascript html css dom
2个回答
1
投票

分配给.textContent属性而不是.innerHTML属性,字符串将被解析为文本而不是HTML(确保只创建文本节点):

document.getElementById("stringLocation").textContent = " <p>Text here</p>"
<pre id="stringLocation"></pre>

1
投票

HTML Character Codes用于此:

&#60;p&#62;test&#60;&#47;p&#62;

&#60;p&#62;test&#60;&#47;p&#62;
© www.soinside.com 2019 - 2024. All rights reserved.