views:

65

answers:

2

Hi all,

I've got a div that looks like this:

<div id="exampleDiv" class="class1 class2" title="example title"></div>

I've selected with JQuery using this statement:

var $div = $('#exampleDiv');

What I'd like to get is a string of the tag itself as html, so that I actually get:

"<div id='exampleDiv' class='class1'....", etc.

Does anyone know of a JQuery function I could use that does this, given the selector? I'm thinking something like $div.htmlHeader() or something like that.

Any help would be appreciated. Thanks.

+5  A: 

Clone the element into a new div, remove the clone's children, and print the parent div's html:

var html = $("<div/>").append($("#exampleDiv").clone().empty()).html();

If the element you want to print has a lot of descendents and you don't want to incur the cost of cloning the entire hierarchy, and if you don't mind briefly leaving the safety of jQuery's DOM interface, you could do this instead:

var html = $("<div/>").append($("#exampleDiv")[0].cloneNode(false)).html();
Sean
+1 This is the way to go! Better than my answer.
patrick dw
A: 

Here you go:

$.fn.tagonly = function() {
    return $('<div/>').append($(this).clone().empty())
        .html().replace(/>(.|[\r\n])*$/ig, '>');
};

Edit Fixed the extra ) and the newline issue. Thanks patrick.

aefxx
@aefxx - Your solution has an extra `)` at the end. Also, I don't think `.*` will match line-breaks. Looks good otherwise. Better than my solution.
patrick dw