Dan Lugg
Dan Lugg

Reputation: 20592

Element creation in jQuery; create, wrap, append

Relatively quick one;

I'm creating a few elements dynamically, and am appending them to another element.

$element = $('<input />', {
    // attributes
}).add('<label />', {
    // attributes
});

This produces <input /><label></label> with their respective attributes and content. I just want to wrap this in a <div> and thought there would be an equally clean way of doing so, but I can't seem to get the following to work:

$element = $('<input />', {
    // attributes
}).add('<label />', {
    // attributes
}).wrapAll('<div />');

If I console.log() my $element, it's only the <input> and <label>. I've also tried

$element = $($('<input />', {
    // attributes
}).add('<label />', {
    // attributes
})).wrapAll('<div />');

Selecting the to-be-appended <input> and <label> elements separately, and applying the .wrapAll(), but that doesn't work either, resulting in the same as above.

Am I close? Should I just go another route?


Ended up going with the following thanks to @mu

$element = $('<div />').append($('<input />', {
    // attr
}).add('<label />', {
    // attr
}));

Oh jQuery; seven million ways to do the same thing, and sometimes you can't figure out one.


Edit

Just adding for future visitors; the append method can also take an array:

$('<div />').append([
    $('<div />'),
    $('<div />'),
    $('<div />'),
]);

Which would yield:

<div>
    <div></div>
    <div></div>
    <div></div>
</div>

So you don't need to chain calls to append().

Upvotes: 0

Views: 2368

Answers (3)

N1ck
N1ck

Reputation: 2001

element = $('<div></div').html($('<input />', {
    // attributes
}).add('<label />', {
    // attributes
}));

Upvotes: 2

sente
sente

Reputation: 2367

If I understand you correctly, I think you might want to use .appendTo() instead of .wrapAll()

Upvotes: 1

mu is too short
mu is too short

Reputation: 434585

Why not just do this?

var $div = $('<div>').append($element);

For example: http://jsfiddle.net/ambiguous/CQDe8/1/

Upvotes: 5

Related Questions