8

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?

Gideon
  • 1,469
  • 2
  • 26
  • 57
  • 1
    It does not matter that it's detached. `html()` returns the empty string because it has no contents. `html()` is the inner html, not the outer html. – Oriol Dec 08 '16 at 14:07

2 Answers2

19

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>
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

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

x[0].outerHTML
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202