[英]How do I convert a JavaScript DOM element (and its entire structure) into string (without jQuery)? ..and re-display it on the page as text?
I'm currently trying to grab a DOM Element (and its entire sub-elements) and store it as string, so that I could re-display it as plain text on the page. 我目前正在尝试获取DOM元素(及其整个子元素)并将其存储为字符串,以便我可以在页面上将其重新显示为纯文本。 Similar to this below:
与此类似:
// Get DOM Element
var x = document.getElementById("para1");
// Create a new DOM Element and display x as text on the page
var div = document.createElement('div');
div.textContent = x;
document.body.appendChild(div);
I was expecting I would get something like <ul><li>One</li><li>Two</li><li>Three</li></ul>
; 我原以为我会得到像
<ul><li>One</li><li>Two</li><li>Three</li></ul>
; however, what I got instead was [object HTMLUListElement]
. 但是,我得到的是
[object HTMLUListElement]
。
Here's the fiddle: http://output.jsbin.com/wesosu/1 这是小提琴: http : //output.jsbin.com/wesosu/1
Use x.outerHTML
to get the HTML content including the element itself 使用
x.outerHTML
获取HTML内容,包括元素本身
var div = document.createElement('div');
div.textContent = x.outerHTML; // x.innerHTML instead if you only want the contents
document.body.appendChild(div);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.