javascript 获取 html 元素作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12612709/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:40:06  来源:igfitidea点击:

get html element as a string

javascriptjqueryhtml

提问by gruber

Possible Duplicate:
jQuery, get html of a whole element

可能的重复:
jQuery,获取整个元素的 html

lets say I have:

可以说我有:

<span>my span</span>

I would like have html as a string of this span

我想要 html 作为这个跨度的字符串

I use:

我用:

var mySpan = $('span');

var mySpan = $('span');

what to do with the mySpan var to have as a result string "<span>my span</span>"

如何处理 mySpan var 作为结果字符串 "<span>my span</span>"

thanks for any help

谢谢你的帮助

回答by Igor Shastin

I think this will help: http://jsfiddle.net/HxU7B/2/.

我认为这会有所帮助:http: //jsfiddle.net/HxU7B/2/



UPDATE.

更新。

mySpan[0].outerHTMLwill take a previoulsy selected node and get a native outerHTMLproperty. Since old Firefox versions doesn't have that property, we can use a bit of hack to get html - simply clone node to dummy divand then get this div's innerHTML: $('<div/>').append(mySpan.clone()).html()

mySpan[0].outerHTML将采用先前选定的节点并获得本机outerHTML属性。由于旧的 Firefox 版本没有该属性,我们可以使用一些 hack 来获取 html - 只需将节点克隆为虚拟节点div,然后获取此 div 的 innerHTML:$('<div/>').append(mySpan.clone()).html()

回答by Joe Coder

jQuery can't do that, but regular JavaScript DOM objects can:

jQuery 不能这样做,但常规的 JavaScript DOM 对象可以:

var mySpanString = $('span').get(0).outerHTML;

回答by prashanth

As others have stated, you could use outerHTMLor clone -> append -> html()

正如其他人所说,您可以使用outerHTMLclone -> append -> html()

But here is another way to do it,

但这里有另一种方式来做到这一点,

var nodeName = mySpan[0].nodeName.toLowerCase();
var outerHtml = "<"+nodeName +">"+mySpan.html()+"</"+nodeName +">";