Get selected element's outer HTML

前端 未结 30 2986
礼貌的吻别
礼貌的吻别 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:14

    Here is a very optimized outerHTML plugin for jquery: (http://jsperf.com/outerhtml-vs-jquery-clone-hack/5 => the 2 others fast code snippets are not compatible with some browsers like FF < 11)

    (function($) {
    
      var DIV = document.createElement("div"),
          outerHTML;
    
      if ('outerHTML' in DIV) {
        outerHTML = function(node) {
          return node.outerHTML;
        };
      } else {
        outerHTML = function(node) {
          var div = DIV.cloneNode();
          div.appendChild(node.cloneNode(true));
          return div.innerHTML;
        };
      }
    
      $.fn.outerHTML = function() {
        return this.length ? outerHTML(this[0]) : void(0);
      };
    
    })(jQuery);
    

    @Andy E => I don't agree with you. outerHMTL doesn't need a getter AND a setter: jQuery already give us 'replaceWith'...

    @mindplay => Why are you joining all outerHTML? jquery.html return only the HTML content of the FIRST element.

    (Sorry, don't have enough reputation to write comments)

提交回复
热议问题