I’m looking to create an element dynamically with jQuery and put another element dynamically within that, but before I append it.
For example, I want the output to look like so:
<span class="imageContainer">
<p>Close</p>
<img src="image.jpg" />
<span>
I could use the following, but it prevents me from using the other method of supplying the attributes:
$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>').prependTo('body');
I’m currently creating the span element with this code, and would like to know how I can append code to it before I append it to anything, this is probably a simple solution that I’m just overlooking:
$('<span/>', {
'id': 'imageContainer'
});
The reason I want to use this method, is so I can attach click methods and such in one go.
UPDATED SOLUTION (thanks to @ParvSharma):
function hoverBox( url, e ) {
var hoverbox = $( '<span/>', {
'id': 'imageContainer',
'style': 'top:'+e.pageY+'px; left:'+e.pageX+'px;'
}).append(
$('<p/>', {
html: 'Close',
click: function() {
var parentContainer = '#'+$(this).parent().attr('id');
destroy( parentContainer );
}
})
).append(
$('<img/>', {
'src': url
})
);
return hoverbox;
}
make the span
var span = $('<span/>', { 'id': 'imageContainer'});then just do
span.append($("<p></p>"));then jo
span.append($("<img></img>"));