从HTMLDivElement创建的字符串 [英] Create string from HTMLDivElement
本文介绍了从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( "<" , "<" ).replace( ">" , ">");
outputNode.innerHTML += escapedStr;
请注意,属性,如阶级,ID等被正确字符串化是值得商榷的。
Note, attributes like "class" , "id" , etc being stringified properly is questionable.
这篇关于从HTMLDivElement创建的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文