Get selected element's outer HTML

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

    I used Jessica's solution (which was edited by Josh) to get outerHTML to work on Firefox. The problem however is that my code was breaking because her solution wrapped the element into a DIV. Adding one more line of code solved that problem.

    The following code gives you the outerHTML leaving the DOM tree unchanged.

    $jq.fn.outerHTML = function() {
        if ($jq(this).attr('outerHTML'))
            return $jq(this).attr('outerHTML');
        else
        {
        var content = $jq(this).wrap('
    ').parent().html(); $jq(this).unwrap(); return content; } }

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

    Hope someone finds it useful!

提交回复
热议问题