How do you convert a jQuery object into a string?
Asked Answered
G

12

435

How do you convert a jQuery object into a string?

Guanine answered 17/3, 2009 at 1:38 Comment(0)
H
653

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');
Hamo answered 17/3, 2009 at 1:44 Comment(12)
It sucks that there isn't a method to just do this, but this is a great solution regardless.Luxuriant
this removes the head and body tagsBogeyman
Note that outerHTML only works if there is a single outer element. $("<p></p><p></p>").prop('outerHTML') will yield "<p></p>", which may not be what you want. You'll have to wrap it in a <div/> or something.Cetane
@Cetane That isn't a valid DOM node, though, so it would be wrong to try to call outerHTML on it to begin with. (Only a tiny subset of what can go in $(...) is a valid DOM node.)Hamo
@JohnFeminella exactly. Don't confuse a jQuery object (as per the question) with a DOM node. :)Cetane
@Cetane My point is that, presumably, since you know what you're passing into it, you also know whether it is a valid DOM node or not. Therefore, you should not call prop('outerHTML') unless you're sure it is a DOM node. (The OP never clarified what he meant by "a string", since any string representation you can imagine is possible, so it seems like most people assumed they were referring to a DOM node that could be directly represented in HTML.)Hamo
What is wrong with $('#item-of-interest').html()?Maxiemaxilla
@Maxiemaxilla it gives you inner html, or simplier, what is inside of element, while outerHtml gives you element as a wholeGeorg
The 2014 version worked perfectly. I found another answer that suggested just using element.outerHTML, but that didn't work. element.prop('outerHTML') did the trick, though.Firmament
Note, that you will lose dataForswear
After using the $(element).html() solution for a year, I discovered it does not work for elements within the <head>...</head> block. But, prop('outerHTML') works on those.Firmament
It would be nice to just remove the reference to html() and keep the update so as not to waste our time with stuff that doesn't work.Race
P
208

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

$('#element-of-interest').prop('outerHTML');
Pasho answered 29/9, 2011 at 3:18 Comment(1)
@Jean-PhilippeLeclerc On Firefox 15.0.1 (linux) it works like a charm.Adamis
B
57

Just use .get(0) to grab the native element, and get its outerHTML property:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);
Biogenesis answered 16/3, 2012 at 11:37 Comment(1)
So much better as it retains my attributes as well. Thanks!Decurion
D
23

Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:

HTML snippet:

<p><b>This is some text</b></p>

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>
Deuce answered 17/3, 2009 at 1:47 Comment(0)
B
10

The best way to find out what properties and methods are available to an HTML node (object) is to do something like:

console.log($("#my-node"));

From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:

var node = $("#my-node").outerHTML;
Bench answered 17/11, 2011 at 11:55 Comment(2)
it's $('#my-node').get(0).outerHTML as in mppfiles' answerBabylonian
.outerHTML didn't work for me, but .prop('outerHTML') did.Illiteracy
O
8

jQuery is up in here, so:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

Return all that HTML stuff:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
Over answered 13/5, 2011 at 10:26 Comment(0)
V
5

This seems to work fine for me:

$("#id")[0].outerHTML
Vomer answered 9/6, 2011 at 12:11 Comment(1)
I was also using this but this doesn't seem to work for Firefox 6.0.1.Corneliuscornell
C
5

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

var htmlElements = $('<p><a href="http://google.com">google</a></p>↵↵<p><a href="http://bing.com">bing</a></p>'),
    htmlString = '';
    
htmlElements.each(function () {
    var element = $(this).get(0);

    if (element.nodeType === Node.ELEMENT_NODE) {
        htmlString += element.outerHTML;
    }
    else if (element.nodeType === Node.TEXT_NODE) {
        htmlString += element.nodeValue;
    }
});

alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ciracirca answered 30/3, 2016 at 11:36 Comment(1)
Thanks man, the accepted answer did not work for me. Yours did!Eugenle
T
1

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()
Topflight answered 13/2, 2012 at 18:37 Comment(2)
But doesn't wrap() return the wrapped element, not the element with which it was wrapped? So this should give the html of the #item-of-interest not it's parent div element (unless jQuery's changed since February of 2012).Midship
Seeing this 10 years later. I just checked and you're right, the wrap is messing it up. It should have been $('#item-of-interest').wrap('<div></div>').parent().html(). But now there is the better native solution in the updated answer.Topflight
H
0

It may be possible to use the jQuery.makeArray(obj) utility function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
Historiography answered 26/4, 2012 at 4:48 Comment(0)
C
0

If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:

// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')

// now 'e_str' is a unique query for this element that can be stringify 
var e_str = e.tagName
  + ( e.id != "" ? "#" + e.id : "")
  + ( e.className != "" ? "." + e.className.replace(' ','.') : "");

//now you can stringify your element to JSON string
var e_json = JSON.stringify({
  'element': e_str
})

than

//parse it back to an object
var obj = JSON.parse( e_json )

//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )

//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
Cacie answered 15/12, 2016 at 15:14 Comment(0)
S
-4
new String(myobj)

If you want to serialize the whole object to string, use JSON.

Somewise answered 17/3, 2009 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.