Get selected element's outer HTML

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 object (a table row in this case, where .html() only returns the cells inside the row).

I've searched around and found a few very 'hackish' type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml functionality?


2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.

This site seems to have a solution for you : jQuery: outerHTML | Yelotofu

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

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
$('.classSelector')[0].outerHTML

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

  • No need to generate a function for it. Just do it like this:

    $('a').each(function(){
        var s = $(this).clone().wrap('<p>').parent().html();
        console.log(s);
    });
    

    (Your browser's console will show what is logged, by the way. Most of the latest browsers since around 2009 have this feature.)

    The magic is this on the end:

    .clone().wrap('<p>').parent().html();
    

    The clone means you're not actually disturbing the DOM. Run it without it and you'll see p tags inserted before/after all hyperlinks (in this example), which is undesirable. So, yes, use .clone() .

    The way it works is that it takes each a tag, makes a clone of it in RAM, wraps with p tags, gets the parent of it (meaning the p tag), and then gets the innerHTML property of it.

    EDIT : Took advice and changed div tags to p tags because it's less typing and works the same.

    链接地址: http://www.djcxy.com/p/46352.html

    上一篇: 用Java增加Map值的最有效方法

    下一篇: 获取选定元素的外部HTML