views:

34

answers:

2

I was wondering if anyone knew a better way to write this block of code.

if($('div.homeBox > div').length > 0){
  $('div.homeBox > div').remove();
}
$('div.homeBox').append(data.loadPage);

This works as it is, but I would like to make it pretty if possible. I am replacing a block of code in my page with HTML data returned by an ajax request (data.loadPage).

An example of data.loadPage would be

<div id="variousIDs" >
    ... some content ...
</div >

Thanks in advance for any advice.

A: 

Give the div inside div.homeBox its own id (e.g., "id=homeBoxInnerDiv" or something), then

if($('#homeBoxInnerDiv').visible()){
$('#homeBoxInnerDiv').replaceWith(data.loadPage);
}

this will replace the contents of the div you want to remove with the new content.

frabjousB
+1  A: 
// you don't need to test if it exists first
$('div.homeBox > div').remove()
$('div.homeBox').append(data.loadPage);

// if you want to do it in one go, this less clear option should work, too:
// .end() moves back up the stack to undo the last filter operation (.children())
$('div.homeBox').children('div').remove().end().append(data.loadPage);

// if you want to get rid of everything within homebox, this is even easier:
$('div.homeBox').empty().append(data.loadPage);
Michael Haren
this is exactly what i was looking for, thanks for the quick reply.
stmpy