How to get string representation from jQuery object?

Really a dumb question, but for example this one:

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

How can I return '<div>bar</div>' ?

+4
source share
2 answers

You need to add it to the container and then call .html() .

This is because .html() provides you only content.

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

 var $foo = $('<div>bar</div>'); $('<div />').append($foo).html(); 
+7
source

Can

 var txt = $foo.text(); 

If you want everything in your element:

 var html = $foo.html(); 

edit - oh wait; you also need an external tag. Hm. Well, you can clone it, wrap it in another div and get text or html from it, but something tells me that there might be a better way:

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

(or do it as @patrick suggests anything.)

0
source

All Articles