outerHTML jQuery 插件

Avatar of Chris Coyier
Chris Coyier

innerHTML() 是原生的,它返回 DOM 节点的内容(例如 <span>I live inside a div.</span>)。outerHTML() 不是,它将包括当前 DOM 节点(例如 <div><span>I live inside a div.</span></div>)。这是一个可链式 jQuery 版本,用于执行此操作。

$.fn.outerHTML = function(){
 
    // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
    return (!this.length) ? this : (this[0].outerHTML || (
      function(el){
          var div = document.createElement('div');
          div.appendChild(el.cloneNode(true));
          var contents = div.innerHTML;
          div = null;
          return contents;
    })(this[0]));
 
}