5

I have the following HTML

<label class="editable" id="user_info_username">Hai world...</label>

now on click function i need the content of the clicked element .

i tried

$(".editable").live("click",function(){
alert($(this).html())  //returns Hai world...
});

But i need the HTML content

so <label class="editable" id="user_info_username">Hai world...</label>

Red
  • 6,230
  • 12
  • 65
  • 112

5 Answers5

6

Clone the clicked element, wrap it in a <div>, and then ask for the HTML of that - something like:

var html = $('<div/>').append($(this).clone()).html();

Working demo at http://jsfiddle.net/f88kj/

I also previously wrote a plugin that does this at https://stackoverflow.com/a/6509421/6782

(function($) {
    $.fn.outerhtml = function() {
        return $('<div/>').append(this.clone()).html();
    };
})(jQuery);
Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
3

if I well understood you need something like .outerHTML property for jQuery

http://forum.jquery.com/topic/jquery-outerhtml-for-jquery

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

What you're looking for is something like outerHTML. Unfortunately, Firefox does not currently support it, so look for a work-around here: How do I do OuterHTML in firefox?.

Community
  • 1
  • 1
Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
1

Maybe you could use a wrapper, like described below:

html:

<div class="YourHtmlContent">
<label class="editable" id="user_info_username">Hai world...</label>
</div>

and js:

$(".editable").live("click",function(){
alert($('.YourHtmlContent').html())
});
Nick N.
  • 12,902
  • 7
  • 57
  • 75
1

The answer using jQuery.clone() is best IMO, but I'm adding this here as it's another way and might be helpful to others.

You could get the html of whatever the parent div is - this is an issue because there might be siblings which would also be returned.

like so:

alert($(this).parent().html()); //will return siblings too

http://jsfiddle.net/Qg9AL/

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85