Get selected element's outer HTML

2018-12-30 23:48发布

I'm trying to get the HTML of a selected object with jQuery. I am aware of the .html() function; the issue is that I need the HTML including the selected object (a table row in this case, where .html() only returns the cells inside the row).

I've searched around and found a few very ‘hackish’ type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml functionality?

标签: jquery
28条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 00:25

Simple solution.

var myself = $('#div').children().parent();
查看更多
公子世无双
3楼-- · 2018-12-31 00:26

Short and sweet.

[].reduce($('.x'), function(i,v) {return i+v.outerHTML}, '')

or event more sweet with help of arrow functions

[].reduce.call($('.x'), (i,v) => i+v.outerHTML, '')

or without jQuery at all

[].reduce.call(document.querySelectorAll('.x'), (i,v) => i+v.outerHTML, '')

or if you don't like this approach, check that

$('.x').get().reduce((i,v) => i+v.outerHTML, '')
查看更多
倾城一夜雪
4楼-- · 2018-12-31 00:27

I came across this while looking for an answer to my issue which was that I was trying to remove a table row then add it back in at the bottom of the table (because I was dynamically creating data rows but wanted to show an 'Add New Record' type row at the bottom).

I had the same issue, in that it was returning the innerHtml so was missing the TR tags, which held the ID of that row and meant it was impossible to repeat the procedure.

The answer I found was that the jquery remove() function actually returns the element, that it removes, as an object. So, to remove and re-add a row it was as simple as this...

var a = $("#trRowToRemove").remove();            
$('#tblMyTable').append(a);  

If you're not removing the object but want to copy it somewhere else, use the clone() function instead.

查看更多
深知你不懂我心
5楼-- · 2018-12-31 00:28

Anothe similar solution with added remove() of the temporary DOM object.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 00:33

Extend jQuery:

(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  };
})(jQuery);

And use it like this: $("#myTableRow").outerHTML();

查看更多
君临天下
7楼-- · 2018-12-31 00:33

you can also just do it this way

document.getElementById(id).outerHTML

where id is the id of the element that you are looking for

查看更多
登录 后发表回答