如何将HTMLElement转换为字符串 [英] How to convert a HTMLElement to a string

查看:1655
本文介绍了如何将HTMLElement转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在javascript中创建一个xml元素以与服务器端交换数据。我发现我可以用document.createElement.But做到这一点,但我不知道如何将其转换为字符串。浏览器中是否有任何API使其更容易?或者是否有任何js lib在琢磨这个API?

在此先感谢。

//修改

>

我发现浏览器API XMLSerializer,它应该是序列化为字符串的正确方法。 div>

通过克隆元素
,可以获得'outer-html',并将其添加到空的'offstage'容器,
和读取容器的innerHTML。



这个例子接受一个可选的第二个参数。


$ b 调用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;
}


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 lib incudling this API?

Thanks in advance.

//Modification

I found that browser API XMLSerializer, it should be the right way to serialize to string.

解决方案

You can get the 'outer-html' by cloning the element, adding it to an empty,'offstage' container, and reading the container's innerHTML.

This example takes an optional second parameter.

Call document.getHTML(element, true) to include the element's descendents.

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

这篇关于如何将HTMLElement转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆