Javascript 如何将 HTMLElement 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2474605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a HTMLElement to a string
提问by xiao Х
I am going to create an XML element in JavaScript to exchange data with server side. I found I can do it with document.createElement. But I do not know how to convert it to string. Is there any API in browser to make it easier? Or is there any JS library including this API?
我将在 JavaScript 中创建一个 XML 元素来与服务器端交换数据。我发现我可以用document.createElement. 但我不知道如何将其转换为字符串。浏览器中是否有任何 API 使其更容易?或者是否有任何包含此 API 的 JS 库?
EDIT:I found that browser API XMLSerializer, it should be the right way to serialize to string.
编辑:我发现浏览器 API XMLSerializer,它应该是序列化为字符串的正确方法。
采纳答案by kennebec
You can get the 'outer-html' by cloning the element, adding it to an empty,'offstage' container, and reading the container's innerHTML.
您可以通过克隆元素、将其添加到一个空的“offstage”容器并读取容器的innerHTML 来获取“outer-html”。
This example takes an optional second parameter.
此示例采用可选的第二个参数。
Call document.getHTML(element, true) to include the element's descendents.
调用 document.getHTML(element, true) 以包含元素的后代。
document.getHTML= function(who, deep){
if(!who || !who.tagName) return '';
var txt, ax, el= document.createElement("div");
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
if(deep){
ax= txt.indexOf('>')+1;
txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
}
el= null;
return txt;
}
回答by gpmcadam
The element outerHTMLproperty (note: supported by Firefox after version 11) returns the HTML of the entire element.
elementouterHTML属性(注意:Firefox 11 版本后支持)返回整个元素的 HTML。
Example
例子
<div id="new-element-1">Hello world.</div>
<script type="text/javascript"><!--
var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>
--></script>
Similarly, you can use innerHTMLto get the HTML contained within a given element, or innerTextto get the text inside an element (sans HTML markup).
同样,您可以使用innerHTML获取给定元素中包含的 HTML,或innerText获取元素中的文本(无 HTML 标记)。
See Also
也可以看看
回答by Navid Sheikh
The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.
最简单的方法是将该元素的 innerHTML 复制到 tmp 变量并将其设为空,然后追加新元素,然后将 tmp 变量复制回它。这是我用来将 jquery 脚本添加到头顶的示例。
var imported = document.createElement('script');
imported.src = 'http://code.jquery.com/jquery-1.7.1.js';
var tmpHead = document.head.innerHTML;
document.head.innerHTML = "";
document.head.append(imported);
document.head.innerHTML += tmpHead;
That simple :)
就这么简单:)
回答by Jnr
I was using Angular, and needed the same thing, and landed at this post.
我正在使用 Angular,需要同样的东西,并登陆了这篇文章。
@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;
回答by Miguel
This might not apply to everyone case, but when extracting from xml i had this problem, which i solved with this.
这可能不适用于所有情况,但是从 xml 中提取时我遇到了这个问题,我用这个解决了。
function grab_xml(what){
var return_xml =null;
$.ajax({
type: "GET",
url: what,
success:function(xml){return_xml =xml;},
async: false
});
return(return_xml);
}
then get the xml:
然后获取xml:
var sector_xml=grab_xml("p/sector.xml");
var tt=$(sector_xml).find("pt");
Then I then made this function to extract xml line , when i need to read from an XML file, containing html tags.
然后,当我需要从包含 html 标签的 XML 文件中读取时,我使用了这个函数来提取 xml 行。
function extract_xml_line(who){
var tmp = document.createElement("div");
tmp.appendChild(who[0]);
var tmp=$(tmp.innerHTML).html();
return(tmp);
}
and now to conclude:
现在得出结论:
var str_of_html= extract_xml_line(tt.find("intro")); //outputs the intro tag and whats inside it: helllo <b>in bold</b>
回答by Richard JP Le Guen
There's a tagNameproperty, and a attributesproperty as well:
有一个tagName属性,还有一个attributes属性:
var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
var attrib = element.attributes[i];
openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);
See also How to iterate through all attributes in an HTML element?(I did!)
另请参阅如何遍历 HTML 元素中的所有属性?(我做到了!)
To get the contents between the open and close tags you could probably use innerHTMLif you don't want to iterate over all the child elements...
要获取打开和关闭标签之间的内容,innerHTML如果您不想遍历所有子元素,您可能会使用它...
alert(element.innerHTML);
... and then get the close tag again with tagName.
...然后再次使用tagName.
var closeTag = "</"+element.tagName+">";
alert(closeTag);

