Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make jQuery output *actual markup*?

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

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

I want to be able to extract the plain-text string

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

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

like image 830
helloluis Avatar asked Mar 04 '10 00:03

helloluis


2 Answers

Yes, you can use the html() function

i.e.

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

Will return 'Hi There!'

Keep in mind this uses innerHTML, so

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

will return

<b>Foo</b>

As a result you'll need to wrap your code in a surrounding div or span.

like image 176
James Davies Avatar answered Sep 29 '22 20:09

James Davies


You can use a outerHTML plugin for that. Here is one:

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

Usage:

alert($("<strong></strong>").text("foo").outerHTML());
// alerts <strong>foo</strong>
like image 25
karim79 Avatar answered Sep 29 '22 19:09

karim79