3

Possible Duplicate:
jQuery - Get selected element's outer HTML

so I have a div..

<div id="fred">

it has stuff in it

<div id="fred">
  <tr id="thing1">hello1</tr>
  <tr id="thing2">hello2</tr>
</div>

if I call

$("#fred").html();

I get just the items inside:

  <tr id="thing1">hello1</tr>
  <tr id="thing2">hello2</tr>

I want the whole thing:

<div id="fred">
  <tr id="thing1">hello1</tr>
  <tr id="thing2">hello2</tr>
</div>

I know that I can ref using this[0], but it seems like there should be an easier way..

I tried .andSelf() but apparently that doesn't do what I thought it should doo..

Community
  • 1
  • 1
KevinDeus
  • 11,988
  • 20
  • 65
  • 97

2 Answers2

3

jQuery doesn't support outerHTML: http://api.jquery.com/html/#comment-84945158

(.andSelf is for element sets, not for depth.)

I think the best solution would be el[0].outerHTML (no extra 'plugin' required and native JS s always good)

Rudie
  • 52,220
  • 42
  • 131
  • 173
0

Get selected element's outer HTML

EDIT: I'll elaborate...

This plugin does the job:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}

you can then simply call:

$('#myTag').outerHTML()
Community
  • 1
  • 1
James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Pointing to someone else's answer isn't really an answer in itself... – lonesomeday Apr 25 '11 at 17:54
  • this seems to be an IE only solution.. – KevinDeus Apr 25 '11 at 17:55
  • Okay, should have put it in the comment I guess. This it not IE only and the edit to my answer is not valid, newish here, I will edit if possible. – James Montagne Apr 25 '11 at 17:57
  • @lonesomeday Maybe we should leave answers in comments then, so the question never gets answered... then we have a bunch of unanswered questions, because we can't mark a question as a solution. Pointing to someone else's answer IS an answer. Otherwise, you could *never* answer a question. period. – cwharris Apr 25 '11 at 17:58
  • with all due respect, kingjiv, cross-browser is why you use JQuery – KevinDeus Apr 25 '11 at 17:58
  • this solution is NOT IE only. The outerhtml property is IE only, this is a jQuery equivilent that is cross-browser. – James Montagne Apr 25 '11 at 18:00
  • @xixonia If you're going to point to another person's answer, put it in a comment -- it's not fair to earn rep for someone else's answer. – lonesomeday Apr 25 '11 at 18:01
  • That's no inefficient and nasty and slow... If you're cloning nodes, at least do it natively and not using a thick jQuery layer. – Rudie Apr 25 '11 at 18:04