scader
scader

Reputation: 525

Return HTML tag as string using JQuery

I created a DOM fragment using JQuery:

var $content = $("<div /", {id:"content"})

I want to output the fragment as a string, so I attempted:

$content.html();

That returns an empty string, because there are no children. How can I return a string containing:

<div id="content" />

Upvotes: 4

Views: 2246

Answers (2)

sinemetu1
sinemetu1

Reputation: 1726

Here is a link to a previously answered question that I think fits what you're looking for.

Also it would would probably be best if your first line of code is written like:

var $content = $("<div></div>", {id:"content"});

This way it's valid html.

Upvotes: 0

user1106925
user1106925

Reputation:

jQuery doesn't have anything in its API to do this directly, but you can use the native .outerHTML property.

$content[0].outerHTML

...but Firefox doesn't support this, so you can do something like this...

$content[0].outerHTML || $('<div>').append($content.clone()).html();

http://jsfiddle.net/m22fn/

Note that a <div> tag doesn't self-close.

Upvotes: 5

Related Questions