Get selected element's outer HTML

前端 未结 30 2386
礼貌的吻别
礼貌的吻别 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:07

    I believe that currently (5/1/2012), all major browsers support the outerHTML function. It seems to me that this snippet is sufficient. I personally would choose to memorize this:

    // Gives you the DOM element without the outside wrapper you want
    $('.classSelector').html()
    
    // Gives you the outside wrapper as well only for the first element
    $('.classSelector')[0].outerHTML
    
    // Gives you the outer HTML for all the selected elements
    var html = '';
    $('.classSelector').each(function () {
        html += this.outerHTML;
    });
    
    //Or if you need a one liner for the previous code
    $('.classSelector').get().map(function(v){return v.outerHTML}).join('');
    

    EDIT: Basic support stats for element.outerHTML

    • Firefox (Gecko): 11 ....Released 2012-03-13
    • Chrome: 0.2 ...............Released 2008-09-02
    • Internet Explorer 4.0...Released 1997
    • Opera 7 ......................Released 2003-01-28
    • Safari 1.3 ...................Released 2006-01-12

提交回复
热议问题