10

Suppose I have the following HTML element:

<span id='kuku' class='lala bubu' 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>?

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

4 Answers4

16

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):

Community
  • 1
  • 1
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • Firefox 11 added support for element.outerHTML. https://developer.mozilla.org/en-US/docs/DOM/element.outerHTML – Jared Apr 23 '13 at 19:42
7

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
p.campbell
  • 98,673
  • 67
  • 256
  • 322
3

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.

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
1

Simply get the owner of the span. So use the id of the owner/container of the span and use

document.getElementById("urSpanOwnerID").innerHTML

WGF
  • 11
  • 2