Get selected element's outer HTML

前端 未结 30 2345
礼貌的吻别
礼貌的吻别 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: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('
    ').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('
    ').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().

提交回复
热议问题