mrblah
mrblah

Reputation: 103607

Appending an error message, want to clear the div first

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?

Upvotes: 3

Views: 22768

Answers (5)

karim79
karim79

Reputation: 342665

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.

Upvotes: 11

Ali
Ali

Reputation: 253

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

so:

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

Upvotes: 0

Ali
Ali

Reputation: 253

this is how I went about it

$(document).ready(function() {
        $('.err').click(function() {
            $('.err').empty().text('Massive Error has occured. ooof!!!');
        });
    });

Upvotes: 1

Tomas Aschan
Tomas Aschan

Reputation: 60634

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.

Upvotes: 3

Adrian Godong
Adrian Godong

Reputation: 8921

You can call

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

before you append the new div element.

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

Upvotes: 4

Related Questions