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,419
  • 2
  • 22
  • 55
  • 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

18

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
  • 129,808
  • 12
  • 152
  • 166
2

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

x[0].outerHTML
Gone Coding
  • 90,552
  • 24
  • 176
  • 195