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