Convert a jQuery object and contents to string?

DA. picture DA. · Jan 4, 2010 · Viewed 26.8k times · Source

I'm grabbing various jquery objects to put into an array and later spit out as HTML.

I'm trying to convert the jQuery object to a text string so it can be spit out as HTML later.

I'm using this technique at the moment:

console.log($myObject.clone().wrap('<div></div>').html());

However, that only appears to be grabbing the contents of my object.

For example, if $myObject is <h2>My Title</h2> the above only returns 'My Title' (no H2 tags).

I've also trying using .text() but get the same result.

Is there a way to convert the entire jQuery object into a text string?

Answer

DA. picture DA. · Jan 4, 2010

Well, answering my own question.

console.log($('<div>').append($myObject.clone()).remove().html());

Thanks goes to John Feminella in this thread:

How do you convert a jQuery object into a string?

who references this post:

http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html