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 tried:

 $content.html(); 

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

 <div id="content" /> 
+4
source share
2 answers

jQuery has nothing in its API for this, but you can use your own .outerHTML property.

 $content[0].outerHTML 

... but Firefox does not support this, so you can do something like this ...

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

http://jsfiddle.net/m22fn/

Note that the <div> does not close on its own.

+5
source

Here is a link to a previously asked question, which, it seems to me, fits what you are looking for.

It would also be better if your first line of code was written like this:

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

So it is valid html.

0
source

Source: https://habr.com/ru/post/1394230/


All Articles