longda
longda

Reputation: 10433

How do I get the string representation out of a jQuery object?

Really dumb question but, for instance, given:

var $foo = $('<div>bar</div>');

How would I get the '<div>bar</div>' back out?

Upvotes: 5

Views: 2481

Answers (3)

Sparklellama
Sparklellama

Reputation: 720

$("<h1>Test</h1>")[0].outerHTML

Returns: <h1>Test</h1>

Upvotes: 2

Pointy
Pointy

Reputation: 414036

Maybe

var txt = $foo.text();

If you want everything in your element:

var html = $foo.html();

edit — oh wait; you want the outer tag too. Hmm. Well you could clone it, wrap it in another div, and get the text or html from that, but something tells me there may be a better way:

var $otherFoo = $foo.clone().wrap('<div/');
var html = $otherFoo.parent().html(); // fixed thanks to @patrick dw

(or do it like @patrick suggests; whatever.)

Upvotes: 0

user113716
user113716

Reputation: 322612

You need to append it to a container, then call .html() on that.

This is because .html() only gives you the content.

Try it out: http://jsfiddle.net/ttYXG/

var $foo = $('<div>bar</div>');

$('<div />').append($foo).html();

Upvotes: 7

Related Questions