tags:

views:

16264

answers:

5

How do you get convert a JQuery object to string?

+1  A: 

new String(myobj)

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

Vasil
+18  A: 

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

John Feminella
Excellent response.
Stefan Kendall
It sucks that there isn't a method to just do this, but this is a great solution regardless.
Steve
+2  A: 

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>
Alex Rockwell
Thanks Alex! You helped me!
henrijs
A: 

This is to Alex Rockwell. What he's trying to say (and that's what i'm trying to do here) is how would you take what's inside the following "This is some text" (the "This is some text") and put it as a string? because .html() returns an object.

gtenor
A: 

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;
}
Dario Cangialosi