Javascript – jQuery Create element inside an element

appenddomjavascriptjquery

I've seen many guides online for create a new element in jQuery such as the following code

var input = $('<input>', {
    id: 'FormUsername',
    name: 'username',
    type: 'text',
    value: 'Enter your username...',
    focusin: function() {
        $(this).val('');
    }
}).appendTo(someElement);

This creates one input element and appends it. I want to create a div element and add this input element to it and then append it. How would i go about doing that?

Thanks,
Alex

Best Answer

You can use .wrap() to wrap your element into another one before appending it:

var input = $('<input>', {
    id: 'FormUsername',
    name: 'username',
    type: 'text',
    value: 'Enter your username...',
    focusin: function() {
        $(this).val('');
    }
}).wrap('<div/>').parent().appendTo(someElement);

Note: you'd have to call .parent() because .wrap() does not return the wrapping element

DEMO


You could also do it in several steps if you need to add attributes to the wrapping div, syntax is similar:

var input = $('<input>', { ... });

// create a div element with an ID=wrapper
$('<div/>', { id: 'wrapper' })
    // append the input to it
    .append(input)
    // append the div to "someElement"
    .appendTo(someElement);

DEMO