Reputation: 422
I'm looping through each relevant tag in an XML file and executing this code.
$('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>').appendTo('#content');
$('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#content');
I want to surround product_image and product_title with a div called product_box like this:
<div id="content">
<div class="product_box">
<div class="product_image">My image code</div>
<div class="product_title">My title code</div>
</div>
</div>
Only the content div is written in the HTML and it must remain like this (I can't write the product_box code in there as it is to be generated on each successful find). How do I do this?
Thanks in advance.
Upvotes: 2
Views: 111
Reputation: 340
You can easily get lost in code, when you use jQuery for creating HTML elements. Try to save the seperate elements in variables and arrange them after initialising. Like this:
var div_box = $('<div></div>').addClass('product_box');
var div_image = $('<div></div>').addClass('product_image').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>');
var div_title = $('<div></div>').addClass('product_title').html('<a href="'+url+'">'+title+'</a>');
$('#content').append(div_box.append(div_image).append(div_title));
Upvotes: 5
Reputation: 28995
var box = $('<div class="product_box"></div>');
var product_image = $('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>');
var produc_title = $('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>');
box.append(product_image,product_title).appendTo('.content');
Upvotes: 0
Reputation: 253308
Just use the same syntax to create the .product_box:
element, and then append the other content to that element, instead of to the #content
element.
var product_box = $('<div />', {'class' : 'product_box'}).appendTo('#content');
$('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>').appendTo(product_box);
$('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo(product_box);
Upvotes: 1