stmpy
stmpy

Reputation: 127

Shortening jQuery command

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.

Upvotes: 1

Views: 63

Answers (2)

Michael Haren
Michael Haren

Reputation: 108356

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

Upvotes: 1

frabjousB
frabjousB

Reputation: 104

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.

Upvotes: 0

Related Questions