Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a jQuery object into a string?

How do you convert a jQuery object into a string?

like image 671
chief7 Avatar asked Mar 17 '09 01:03

chief7


People also ask

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Which method converts a given value into a string in jQuery?

The String() method converts a value to a string.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

What is jQuery object?

A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties: length. context. selector.


2 Answers

I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:

$('<div>').append($('#item-of-interest').clone()).html();  

This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.

If you're just after a string representation, then go with new String(obj).

Update

I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:

$('#item-of-interest').prop('outerHTML'); 
like image 83
John Feminella Avatar answered Oct 12 '22 08:10

John Feminella


With jQuery 1.6, this seems to be a more elegant solution:

$('#element-of-interest').prop('outerHTML'); 
like image 43
nickh Avatar answered Oct 12 '22 10:10

nickh