Get selected element's outer HTML

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

    jQuery plugin as a shorthand to directly get the whole element HTML:

    jQuery.fn.outerHTML = function () {
        return jQuery('<div />').append(this.eq(0).clone()).html();
    };
    

    And use it like this: $(".element").outerHTML();

    0 讨论(0)
  • 2020-11-21 05:02

    I came across this while looking for an answer to my issue which was that I was trying to remove a table row then add it back in at the bottom of the table (because I was dynamically creating data rows but wanted to show an 'Add New Record' type row at the bottom).

    I had the same issue, in that it was returning the innerHtml so was missing the TR tags, which held the ID of that row and meant it was impossible to repeat the procedure.

    The answer I found was that the jquery remove() function actually returns the element, that it removes, as an object. So, to remove and re-add a row it was as simple as this...

    var a = $("#trRowToRemove").remove();            
    $('#tblMyTable').append(a);  
    

    If you're not removing the object but want to copy it somewhere else, use the clone() function instead.

    0 讨论(0)
  • 2020-11-21 05:04

    To be truly jQuery-esque, you might want outerHTML() to be a getter and a setter and have its behaviour as similar to html() as possible:

    $.fn.outerHTML = function (arg) {
        var ret;
    
        // If no items in the collection, return
        if (!this.length)
            return typeof arg == "undefined" ? this : null;
        // Getter overload (no argument passed)
        if (!arg) {
            return this[0].outerHTML || 
                (ret = this.wrap('<div>').parent().html(), this.unwrap(), ret);
        }
        // Setter overload
        $.each(this, function (i, el) {
            var fnRet, 
                pass = el,
                inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";
    
            if (!el.outerHTML)
                el = $(el).wrap('<div>').parent()[0];
    
            if (jQuery.isFunction(arg)) { 
                if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
                    el[inOrOut] = fnRet;
            }
            else
                el[inOrOut] = arg;
    
            if (!el.outerHTML)
                $(el).children().unwrap();
        });
    
        return this;
    }
    

    Working demo: http://jsfiddle.net/AndyE/WLKAa/

    This allows us to pass an argument to outerHTML, which can be

    • a cancellable function — function (index, oldOuterHTML) { } — where the return value will become the new HTML for the element (unless false is returned).
    • a string, which will be set in place of the HTML of each element.

    For more information, see the jQuery docs for html().

    0 讨论(0)
  • 2020-11-21 05:04

    If the scenario is appending a new row dynamically, you can use this:

    var row = $(".myRow").last().clone();
    $(".myRow").last().after(row);
    

    .myrow is the classname of the <tr>. It makes a copy of the last row and inserts that as a new last row. This also works in IE7, while the [0].outerHTML method does not allow assignments in ie7

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-21 05:09

    Simple solution.

    var myself = $('#div').children().parent();
    
    0 讨论(0)
提交回复
热议问题