Get selected element's outer HTML

前端 未结 30 2368
礼貌的吻别
礼貌的吻别 2020-11-21 04:50

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 obje

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 05:01

    Note that Josh's solution only works for a single element.

    Arguably, "outer" HTML only really makes sense when you have a single element, but there are situations where it makes sense to take a list of HTML elements and turn them into markup.

    Extending Josh's solution, this one will handle multiple elements:

    (function($) {
      $.fn.outerHTML = function() {
        var $this = $(this);
        if ($this.length>1)
          return $.map($this, function(el){ return $(el).outerHTML(); }).join('');
        return $this.clone().wrap('
    ').parent().html(); } })(jQuery);

    Edit: another problem with Josh's solution fixed, see comment above.

提交回复
热议问题