Get selected element's outer HTML

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

    I have made this simple test with outerHTML being tokimon solution (without clone), and outerHTML2 being jessica solution (clone)

    console.time("outerHTML");
    for(i=0;i<1000;i++)
     {                 
      var html = $("").outerHTML();
     }                 
    console.timeEnd("outerHTML");
    
    console.time("outerHTML2");
    
     for(i=0;i<1000;i++)
     {                 
       var html = $("").outerHTML2();
      }                 
      console.timeEnd("outerHTML2");
    

    and the result in my chromium (Version 20.0.1132.57 (0)) browser was

    outerHTML: 81ms
    outerHTML2: 439ms

    but if we use tokimon solution without the native outerHTML function (which is now supported in probably almost every browser)

    we get

    outerHTML: 594ms
    outerHTML2: 332ms

    and there are gonna be more loops and elements in real world examples, so the perfect combination would be

    $.fn.outerHTML = function() 
    {
      $t = $(this);
      if( "outerHTML" in $t[0] ) return $t[0].outerHTML; 
      else return $t.clone().wrap('

    ').parent().html(); }

    so clone method is actually faster than wrap/unwrap method
    (jquery 1.7.2)

提交回复
热议问题