0

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

3 Answers 3

5

Why not just do this?

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

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

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

1 Comment

Thanks @mu - Spot on indeed. I reworked it a bit using your technique, and its perfect, in fact more readable and brief. I'll accept in 3.
2
element = $('<div></div').html($('<input />', {
    // attributes
}).add('<label />', {
    // attributes
}));

Comments

1

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

Comments

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.