0

I have a small issue that I cannot seem to resolve.

Here goes... I have an input being created like this...

var input = $('<input/>');

If I do this....all is good

$(this).append(input);

If I do this though....

$(this).append('<div>' + input + '</div>');

It appends a div with the html [object Object]

Can someone guide me in the right direction?

Thank you in advance!

2
  • + is for concatenating strings. input is a jQuery object, not a string. Commented Sep 15, 2014 at 16:38
  • I knew this was the issue, I was just not sure if there was a function to convert an object to a string. Commented Sep 15, 2014 at 16:42

2 Answers 2

1

you could

$('<div />').append(input).appendTo(this);

Demo: Fiddle

The problem is input is an jQuery object so when you use it in a string concatenation it will result in [object Object](default toString() for an object);


Or

var input = $('<input/>');
$('<div />', {
    append: input
}).appendTo(this);

Demo: Fiddle

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

6 Comments

Is there a method or function to turn an object into a string?
@VIDesignz see this answer by trueblueaussie- if you want it as a string then why are you creating it as an jQuery object
I find it easier to create as an object, but your question is valid. Is it advisable to just work with objects rather than strings when creating elements?
@VIDesignz I would mostly work with objects... but then at the end I would use that object not the generated string... else I would try to generate the markup directly using strings
@VIDesignz why do you want to have the html for your concatenation where you could easily use the object itself
|
1

You need to work with all strings, or all jQuery objects:

e.g.

$(this).append($('<div>').append(input));

or

$(this).append('<div>' + input[0].outerHTML + '</div>');
// I think this version is ugly :)

Notes:

  • $('<div>') creates a new jQuery DOM element, which can then have child content appended.
  • input[0].outerHTML will return the text string equivalent to the DOM objects HTML

4 Comments

I don't think input.html() will work as .html() will return innerHTML... input element does not have innerHTML
@Arun P Johny: Yep, too quick. Corrected (horrible solution though)
Although all the other answers are pretty much the same, I was after a solution to which could convert an object to a string. This seems to be the way.
Not as pretty, but the DOM outerHTML will do the trick. Good luck with your project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.