从HTMLDivElement创建的字符串

编程入门 行业动态 更新时间:2024-10-27 01:23:07
本文介绍了从HTMLDivElement创建的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想能够做的就是创建一个HTML元素的JavaScript对象的字符串。例如:

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";

现在我们已经创建天 HTMLDivElement对象是有可能使其打印作为一个字符串?例如。

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>

感谢马修

推荐答案

在变阿甘的包装,因为他的实施升降机目标节点出来的文件。

Variant on Gump's wrapper, since his implementation lifts the target node out of the document.

function nodeToString ( node ) { var tmpNode = document.createElement( "div" ); tmpNode.appendChild( node.cloneNode( true ) ); var str = tmpNode.innerHTML; tmpNode = node = null; // prevent memory leaks in IE return str; }

要在屏幕上打印生成的字符串(RE:转义)

To print the resulting string on screen (re: escaped)

var escapedStr = nodeToString( node ).replace( "<" , "&lt;" ).replace( ">" , "&gt;"); outputNode.innerHTML += escapedStr;

请注意,属性,如阶级,ID等被正确字符串化是值得商榷的。

Note, attributes like "class" , "id" , etc being stringified properly is questionable.

更多推荐

从HTMLDivElement创建的字符串

本文发布于:2023-10-28 02:05:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   HTMLDivElement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!