Reputation: 103607
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
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
Reputation: 253
Yes you are right. I meant to say that for append method.
so:
$(".container").empty().append(htmlOfyourerror);
Upvotes: 0
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
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:
<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...<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 =)Upvotes: 3
Reputation: 8921
You can call
$(".container").empty();
before you append the new div element.
Reference: http://docs.jquery.com/Manipulation/empty
Upvotes: 4