4

I have something like this

<ul>
<li class="aclass" id="a">content</li>
<li class="aclass" id="b">content</li>
<li class="aclass" id="c">content</li>
<li class="aclass" id="d">content</li>
<li class="aclass" id="e">content</li>
<li class="aclass" id="f">content</li>
</ul>

I have code like

$(".aclass").live("mousedown",function() {

alert($this.html());

});

This will alert the content, what I would like to do is alert the entire element like

<li class="aclass" id="f">content</li>

I've tried $(this).parent() but that returns the whole UL

jim smith
  • 1,783
  • 3
  • 15
  • 12
  • 1
    exact duplicate of [jQuery - Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/jquery-get-selected-elements-outer-html) – redsquare Dec 23 '10 at 08:49

3 Answers3

6
alert($(this).clone().wrap('<div/>').parent().html());
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
0
alert($('<div/>').append($(this).clone()).html());

http://jsfiddle.net/keegan3d/nfEyQ/

keegan3d
  • 9,117
  • 9
  • 52
  • 73
0

To get the html-code of a DOM-Node you can use the property outerHTML

var html = document.getElementById('someId').outerHTML;

this sadly doesnt work in firefox. But you can use XMLSerializer to achieve the same result. Like this

var elm = document.getElementById('someId');
var xmls = new XMLSerializer();
var html = xmls.serializeToString(elm);

in your jQuery-code this might look something like this:

$(".aclass").live("mousedown",function() {
  alert( this.outerHTML || new XMLSerializer().serializeToString(this)  );
});
kioopi
  • 1,940
  • 1
  • 17
  • 24
  • Seems like XMLSerializer returns proper XML, this might give unexpected results, see: http://stackoverflow.com/questions/1700870/how-do-i-do-outerhtml-in-firefox/3819589#3819589 – kioopi Dec 23 '10 at 09:33