1

Possible Duplicate:
Get selected element’s outer HTML

In jQuery I'm currently using this to get some HTML:

var content = $("tr#add-ingredients-over-here").html();

But, I actually need to include that tr in the selected HTML. I can't figure out how to do this. I also need to replace that with some other HTML after.

Any suggestions on how to do this?

Community
  • 1
  • 1
Mark Topper
  • 339
  • 1
  • 6
  • 14

3 Answers3

2

What you are looking for is the outerHTML of the element. You can try this:

var content = $("#add-ingredients-over-here")[0].outerHTML;

This is supported by all current browsers. Firefox was the last to add support for this in Firefox 11 (March 2012); all other browsers already support this for at least 4 years now. If you must support older browsers than this stackoverflow thread has a jQuery-based implementation that works everywhere:

jQuery.fn.outerHTML = function() {
    return $(this).length > 0 ? $(this).clone().wrap('<div />').parent().html() : '';
};
Community
  • 1
  • 1
Wichert Akkerman
  • 4,918
  • 2
  • 23
  • 30
0

Another fully cross browser approach. Makes a clone of tbody, removes all but the row wanted and retrieves the html from it

var content = $("#add-ingredients-over-here")
                   .parent().clone().find('tr:not(#add-ingredients-over-here)').remove()
                    .end().html()

EDIT: WHy can't you just use clone() if you need the whole TR? A clone can be inserted in another table as a jQuery object

/*copy whole row to another table*/
$('#otherTable').append( $("#add-ingredients-over-here").clone() );
charlietfl
  • 170,828
  • 13
  • 121
  • 150
-1

Try

$("tr#add-ingredients-over-here").parent().html();

It will retrieve the parent first, and then return its HTML content

MatRt
  • 3,494
  • 1
  • 19
  • 14
  • 1
    It will also retrieve all other elements of the parent. In this case probably ALL table rows – cowls Jan 13 '13 at 22:58
  • I did not understand you would like only your TR. In this case, you can create a temporary div, insert a clone of your TR inside and then call the html method. The code is: $('
    ').append($('#tr#add-ingredients-over-here').clone()).html();
    – MatRt Jan 13 '13 at 23:14