Reputation: 81
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
Upvotes: 2
Views: 11587
Reputation: 150243
Use the wrap function:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).wrap('<div></div>').parent().appendTo(someElement);
wrap docs:
Description: Wrap an HTML structure around each element in the set of matched elements.
Upvotes: 0
Reputation: 30666
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
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);
Upvotes: 5
Reputation: 69905
You can try this.
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
})
$('<div>', {
id: 'divId',
class: 'className'
})
.append(input)
.appendTo(someElement);
Upvotes: 0
Reputation: 136074
And another way:
$('#someElement').append($('<span></span>').append(input));
Upvotes: 0
Reputation: 6619
This maybe help you:
var div = $("<div>");
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
});
div.html("I'm the div");
div.append(input);
$("body").append(div);
Upvotes: 0
Reputation: 224862
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);
Upvotes: 1