从 HTMLDivElement 创建字符串
我希望能够从 Javascript HTMLElement 对象创建一个字符串。例如:
var day = document.createElement("div");
day.className = "day";
day.textContent = "Random Text";
现在我们已经创建了 day
HTMLDivElement 对象,是否可以将其打印为字符串?例如
<div class="day">Random Text</div>
What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:
var day = document.createElement("div");
day.className = "day";
day.textContent = "Random Text";
Now we have create the day
HTMLDivElement Object is it possible to make it print as a string? e.g.
<div class="day">Random Text</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您也可以直接解析字符串,为什么还要使用
createElement
呢?例如:
var string = '
';
Why would you use
createElement
if you can also directly parse a string?Like:
var string = '<div class="' + class + '">' + text + '</div>';
简单使用函数 outerHTML
了解更多
Simple use the function outerHTML
know more
Gump 包装器的变体,因为他的实现将目标节点从文档中取出。
在屏幕上打印结果字符串(回复:转义)
注意,诸如“class”、“id”等属性是否正确字符串化是有问题的。
Variant on Gump's wrapper, since his implementation lifts the target node out of the document.
To print the resulting string on screen (re: escaped)
Note, attributes like "class" , "id" , etc being stringified properly is questionable.
你可以使用这个函数(取自pure.js)
You can use this function (taken from pure.js)
距离上次的回答已经过去了几年。所以这里有一个更简单的方法:
我发现
.outerHTML
<现在所有主流浏览器都支持 /a>(请参阅 caniuse)。您可以使用它轻松获取 JS 元素的 HTML:
这将记录:
A few years have passed since the last answers. So here is an easier approach:
I found out that
.outerHTML
is supported by all major browsers now (see caniuse).You can use it to get the HTML of an JS element with ease:
This will log:
<div class="day">Random Text</div>
您可以将该元素包装到另一个元素中并在其上使用
innerHTML
:You can wrap that element into another element and use
innerHTML
on it:您需要创建文本节点来为您创建的元素添加文本,如下所示:
You need to create text node to add text for your created element like this:
我的元素是一个带有
element : HTMLDivElement
的对象,所以这对我有用。如果您只有
HTMLDivElement
,那么这应该可以工作:My element was a object with
element : HTMLDivElement
, so this worked for me.If you have just
HTMLDivElement
, then this should work: