Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the outer HTML of a detached JQuery object [duplicate]

I'm creating a html node by jQuery (the sample is of tag <input> but can be of any type):

var x = $("<input>");

Then I add its attributes through a series of .prop() function:

x.prop("id", ...).prop("class", ...);

Now a certain plugin does not support JQuery object, but rather the HTML string so I invoke the plugin through this:

var n = plugin.method1(x.html())

Which I though will work but .html() returns an empty string. Although some said it will be resolved if I append it first on the DOM tree. How can I get its HTML string without appending it first in the DOM tree?

like image 319
Gideon Avatar asked Dec 08 '16 13:12

Gideon


2 Answers

You can use .prop() to get outerHTML property.

x.prop('outerHTML');

var x = $("<input>");
x.prop('id', 'yahooooooooo');
console.log(x.prop('outerHTML'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 179
Satpal Avatar answered Oct 12 '22 08:10

Satpal


Bit simpler to index the HTMLElement behind it and access the outerHTML property like this:

x[0].outerHTML
like image 2
Gone Coding Avatar answered Oct 12 '22 08:10

Gone Coding