tags:

views:

312

answers:

5

Hi,

My HTML looks like and js looks like this:

<div class="container"></div>

var html = "<div class="error">hello</div>";

$(".container").append( $(html) );

Problem is that I don't clear the html inside the div with class=container first, so I keep appending messages to that area.

How can I clear anything inside of the div class="container" first and THEN append my 'html' div?

+5  A: 

Assuming you mean to 'replace' what is in your div, I think what you need to use is:

$(".container").html( html );

A more jQueryish way to do it would be:

$errorDiv = $('<div>hello</div>').addClass('error');
$(".container").html($errorDiv.html());

That has the added benefit of giving you a reference to the error div.

karim79
+3  A: 

You can call

$(".container").empty();

before you append the new div element.

Reference: http://docs.jquery.com/Manipulation/empty

Adrian Godong
+1  A: 

I take the liberty to assume that you're using the container for status messages, and then creating error/success messages on the fly to go inside the container div. If so, I'd suggest going with the following approach instead:

Html:

<div id="status"></div>

Javascript:

function showError(msg) {
    $('#status').html(msg).addClass('error');
}
function showStatus(msg) {
    $('#status').html(msg).removeClass('error');
}

Note the following:

  • As Paolo mentions in his comment, it is much more effective to reference the <div> by an id - that goes directly on the javascript document.getElementById() method, which is way faster than going over the entire DOM tree in search for one element...
  • As you were clearing the contents of the <div class="container"> for each call, I saw no reason to keep it. You could just as well just manipulate the html contents and the css classes of a single div. Faster, and looks nicer in your markup =)
  • You obviously don't need your show status/error message logic in separate methods - I only did so for clarity.
Tomas Lycken
A: 

this is how I went about it

$(document).ready(function() {
        $('.err').click(function() {
            $('.err').empty().text('Massive Error has occured. ooof!!!');
        });
    });
Ali
Doesn't "text" do an implicit empty, replacing whatever was there?
Nosredna
A: 

Yes you are right. I meant to say that for append method.

so:

$(".container").empty().append(htmlOfyourerror);
Ali