2

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.

2
  • You are appending the elements to #content element, but you have a div element with class of content! typo? Commented Nov 14, 2012 at 12:26
  • Thanks, it was a typo, fixed OP now. Commented Nov 14, 2012 at 12:34

3 Answers 3

5

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's nice thanks. Just edited the last line to make it work: $('#content').append(div_box.append(div_image).append(div_title));
1

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);

Comments

0
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');

Reference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.