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
get html element as a string
提问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].outerHTML
will take a previoulsy selected node and get a native outerHTML
property. Since old Firefox versions doesn't have that property, we can use a bit of hack to get html - simply clone node to dummy div
and 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()
正如其他人所说,您可以使用outerHTML或clone -> append -> html()
But here is another way to do it,
但这里有另一种方式来做到这一点,
var nodeName = mySpan[0].nodeName.toLowerCase();
var outerHtml = "<"+nodeName +">"+mySpan.html()+"</"+nodeName +">";