jQuery Create element inside an element

10,864

Solution 1

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

Solution 2

Same syntax, really:

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

var div = $('<div>', {
    id: 'SomeWrapperDiv'
}).append(input);

div.appendTo(someElement);
Share:
10,864
user1246035
Author by

user1246035

Updated on June 04, 2022

Comments

  • user1246035
    user1246035 almost 2 years

    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