How to convert an HTML element to a string, including the opening and closing tags?
Suppose I have the following HTML element:
<span id='kuku' class='lala bubu'开发者_StackOverflow value='xyz'>some text</span>
I know that .html()
returns the inner part of the element, i.e. some text
.
How could I get the whole element as string, containing <span>...</span>
?
Most browsers support the element.outerHTML
property. You may also want to check out the following Stack Overflow post for an alternative solution (for non IE browsers):
- How do I do OuterHTML in firefox?
Try this:
alert($('#kuku').clone().wrapAll("<div/>").parent().html());
- clones the element you want
- wraps it in a div
- selects the parent (the new div)
- gets the 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. It then returns the innerHTML of that previously empty div
, which now has in it precisely the HTML you are after.
Simply get the owner of the span. So use the id of the owner/container of the span and use
document.getElementById("urSpanOwnerID").innerHTML
精彩评论