2

My HTML code is constructed in such a way that it is in following format :

var s = $('<input type="date" id="date-value"/>');

I want to extract the html inside my jQuery selection, as a separate element:

 <input type="date" id="date-value"/>

I tried various inbuilt methods like s.text(), s.innerHTML etc, but they didn't work.

JSFiddle : http://jsfiddle.net/fkgaqtb2/

Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
budhavarapu ranga
  • 483
  • 2
  • 7
  • 15

3 Answers3

1

If you want a new element from the selector, use jQuery's .clone function. alert(s.clone().prop('outerHTML'));

That will output the string it looks like you're trying to get in your fiddle.

In any case, if you just want a string representation of the element, remember that s is a selector, so you'll need jQuery's .prop method. You want:
s.prop('outerHTML').

FYI, this version of the question is similar to another.
Rememeber that HTML elements (not jQuery selections, that's why we need prop) have an outerHTML too, not just innerHTML!

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
0

Create a temporary div, then clone your element and append to it:

alert($('<div>').append(s.clone()).html());
Tuan Anh Hoang-Vu
  • 1,994
  • 1
  • 21
  • 32
0

If you want the outer html, you can use:

var s = $('<input type="date" id="date-value"/>');
$('<div>').append(s.clone()).html();

Or if you need it often, you can add a new method:

$.fn.outerHtml=function(){
    return $('<div>').append(this.clone()).html();
}

And then you can just use: s.outerHtml();

Okku
  • 7,468
  • 4
  • 30
  • 43