Is there a way to draw jQuery * output with actual markup *?

When using jQuery to dynamically build markup, it sometimes becomes useful to return the actual HTML that it generates as a string, rather than as a bunch of jQuery objects. Is there any way to do this? For example, here:

$("<strong></strong>").text("Hi there!");

I want to extract a plain text string

"<strong>Hi there!</strong>"

so that I can cache it remotely. Is there any way to do this?

+5
source share
3 answers

You can use the outerHTML plugin for this. Here is one :

jQuery.fn.outerHTML = function(s) {
    return (s)
    ? this.before(s).remove()
    : jQuery("<p>").append(this.eq(0).clone()).html();
}

Using:

alert($("<strong></strong>").text("foo").outerHTML());
// alerts <strong>foo</strong>
+3
source

Yes, you can use the html () function

i.e.

$("").text("Hi There!").html();

Will come back "Hello!"

, innerHTML,

$("<div><b>Foo</b></div>").html();

<b>Foo</b>

div span.

+3

Just call .html () to get HTML from any element, including generated ones. This is from the Chrome Developer Tool session:

> $("<div><span>blerg</span></div>")
Object
> $("<div><span>blerg</span></div>").html()
<span>blerg</span>

You can see, the first returns an object, the second returns text.

+1
source

All Articles