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/

7
  • 2
    I fail to understand what you are wanting? You are already creating the new element with your append statement (on your fiddle) Commented Jun 8, 2015 at 22:03
  • @EdCottrell Because it doesn't work. But true, the better question is why? Commented Jun 8, 2015 at 22:03
  • Not working. returns a empty value. Commented Jun 8, 2015 at 22:03
  • @JClaspill I am just appending to see whether s is valid or not. But my main intention is to extarct the HTML inside the element. Commented Jun 8, 2015 at 22:04
  • for the value inside the input just use s.val() Commented Jun 8, 2015 at 22:05

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

3 Comments

In that case, wouldn't it be better to mark it as a duplicate?
I sadly don't know how, or don't have the rep/permissions yet. Care to provide a link that explains how to do so? Thanks!
You can click the "flag" option on the question > go to "a duplicate..." > put in the link to the duplicate question > click "vote to close".
0

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

alert($('<div>').append(s.clone()).html());

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.