[英]How to convert an HTML element to a string, including the opening and closing tags?
Suppose I have the following HTML element: 假设我有以下HTML元素:
<span id='kuku' class='lala bubu' value='xyz'>some text</span>
I know that .html()
returns the inner part of the element, ie some text
. 我知道
.html()
返回元素的内部部分,即some text
。
How could I get the whole element as string, containing <span>...</span>
? 我如何将整个元素作为字符串,包含
<span>...</span>
?
Most browsers support the element.outerHTML
property. 大多数浏览器都支持
element.outerHTML
属性。 You may also want to check out the following Stack Overflow post for an alternative solution (for non IE browsers): 您可能还想查看以下Stack Overflow帖子以获取替代解决方案(适用于非IE浏览器):
Try this: 试试这个:
alert($('#kuku').clone().wrapAll("<div/>").parent().html());
You can also do it like this : 你也可以做它喜欢这样 :
alert( $('<div>').append( $("#kuku").clone() ).html() );
This one creates an empty div
and appends a copy / clone of the element with id kuku
to it. 这个创建一个空
div
并将id kuku
的元素的副本/克隆附加到它。 It then returns the innerHTML of that previously empty div
, which now has in it precisely the HTML you are after. 然后它返回之前为空的
div
的innerHTML,现在其中包含您正在使用的HTML。
Simply get the owner of the span. 只需获得跨度的所有者。 So use the id of the owner/container of the span and use
因此,请使用span的所有者/容器的id并使用
document.getElementById("urSpanOwnerID").innerHTML
的document.getElementById( “urSpanOwnerID”)。innerHTML的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.