Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do you get convert a JQuery object to string?

share|improve this question
Rex M: It's useful to be able to do this in a return context. For example: 374 function query_box(tab) 375 { 376 var ta = $("<textarea></textarea>"); 377 ta.attr("id","query_box"); 378 console.log(ta.attr("id")); 379 //ta.val(query.tab); 380 var ret = $( 381 [ 382 ($('<div>').append(ta).clone()).remove().html(), 383 "<br />", 384 "<input value='Run Query' id='run_query_popup' type='submit'/>", 385 "<?=$this->session->userdata?>" 386 ].join("") 387 ); 388 return ret; – g33kz0r Jul 21 '09 at 21:26
42  
HE IS BEING SPECIFIC!! Rex! He is asking..EXACTLY..how to convert jquery object to string. Please tell me what is so hard to understand? Does it matter why? Do you really need a massive story to tell him? You didn't even answer the question. ( I know, the irony). – Zenph Aug 23 '10 at 8:37
2  
I think people like REX that skulk forums and discussion boards, ready to shoot down any person inquiring about an issue simply to get off an ego trip is what we are all, in a way, just simply sick and tired of. Instead of replying with, "why do you need to do that?" or "there is no specific answer to your specific question, it all 'depends'" or my favorite "have you tried googling it?", why not bring something constructive or just don't butt in at all. – user1464296 Aug 30 '12 at 20:45
21  
Who is Rex?!... – AJP Oct 19 '12 at 12:02

11 Answers

up vote 166 down vote accepted

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).

share|improve this answer
4  
Excellent response. – Stefan Kendall Sep 30 '09 at 22:00
14  
It sucks that there isn't a method to just do this, but this is a great solution regardless. – Steve Mar 8 '10 at 16:45
3  
an outerhtml() would be perfect – Sam Jan 31 '11 at 16:58
6  
This works with SVG!!! Cool trick! :D – Cipi Apr 13 '11 at 13:06
this removes the head and body tags – ile Jan 9 at 7:06
show 1 more comment

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

$('#element-of-interest').prop('outerHTML');
share|improve this answer
2  
will not work in firefox – Jean-Philippe Leclerc Feb 9 '12 at 16:52
3  
@Jean-PhilippeLeclerc On Firefox 15.0.1 (linux) it works like a charm. – dave Sep 21 '12 at 13:01
4  
This worked great for me in firefox 19.0 – Nate Flink Feb 26 at 21:43

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>
share|improve this answer
Thanks Alex! You helped me! – henrijs Aug 26 '10 at 20:50
Excellent! Very handy method indeed. – Liutauras Feb 1 '11 at 14:34

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;
share|improve this answer
2  
.outerHTML didn't work for me. Is it documented anywhere? – x3ro Jun 12 '12 at 15:48

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);
share|improve this answer

This seems to work fine for me:

$("#id")[0].outerHTML
share|improve this answer
2  
I was also using this but this doesn't seem to work for Firefox 6.0.1. – mikong Sep 2 '11 at 10:25
new String(myobj)

if you want to serialize the whole object to string use json.

share|improve this answer
1  
this doesn't work (tried with a jquery 1.8 object) – ile Jan 9 at 7:04

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

$('#item-of-interest').wrap('<div></div>').html()
share|improve this answer
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). – David Thomas Jul 7 at 23:07

jQuery up in here so ...

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

return all that html shtuff

$('div' /*elys with html text stuff thatcha want */ ).goodOLauterHTML(); // alerts tags en all
share|improve this answer

There's my implementation of dumpElement:

// example usage
var element = $('head').get()[0];
console.log( dumpElement(element) );

function dumpElement( element ) {

    var elementDump;

    // dump element attributes
    var attrDump = '';

    var attribute;
    var dumpedAttribute;
    for( var i = 0; i < element.attributes.length; i++) {

        attribute = element.attributes[i];

        // skip every not specified attribute (useful for example in IE)
        if ( attribute.specified == false ) continue;

        // current attribute dump
        dumpedAttribute = attribute.name + '="' + attribute.value + '"';

        // add current attribute to dump, separating attributes with whitespace
        attrDump += ((attrDump != '')?' ':'') + dumpedAttribute;
    }

    var tagName = element.tagName.toLowerCase();

    // note: innerHTML does not preserve code formatting
    // note: innerHTML on IE sets the tags names to uppercase (e.g. not W3C Valid)
    if( element.innerHTML == '' ) {

        // self closing tag syntax
        elementDump = '<' + tagName + ((attrDump != '')? ' '+attrDump : '') + '/>';  

    } else {

        elementDump = '<' + tagName + ((attrDump != '')? ' '+attrDump : '') + '>' +
            element.innerHTML +
            '</' + tagName + '>';
    }

    return elementDump;
}
share|improve this answer

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];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.