61

I'm trying to clear the div's innerHTML before repopulating it. I tried removeData() but once that's called, when I try to add the data, I get nothing from the next line after remove whereas if I remove the removeData() it's fine again. I just want to clear out any previous content in that div before I re-populate it.

    divToUpdate.removeData(); //clean out any existing innerHTML div content first
    divToUpdate.html(data);

It looks like it never gets to my divToUpdate.html(data) for some reason after it calls that removeData();

Malady
  • 251
  • 1
  • 12
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471

6 Answers6

119

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

Just do

divToUpdate.html("");

or

divToUpdate.empty();
womp
  • 115,835
  • 26
  • 236
  • 269
29

To remove all child elements from your div:

$('#mysweetdiv').empty();

.removeData() and the corresponding .data() function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:

var $li = $('<li>Joe</li>').data('id', 25);
Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
9
$('div').html('');

But why are you clearing, divToUpdate.html(data); will completely replace the old HTML.

Christopher Altman
  • 4,868
  • 2
  • 33
  • 49
  • because I believe that the div in the parent page is retaining the old innerHTML every time I close and reopen the jQuery UI Dialog – PositiveGuy Apr 15 '10 at 20:12
  • How do you know this? what are you referencing that tells you other than looking at the div content that it clears it out? – PositiveGuy Apr 15 '10 at 20:14
  • In the jQuery documentation (http://api.jquery.com/html/) "A string of HTML to set as the content of each matched element." I interpret the work "set" to mean replace. To verify this I could do something like alert($('div').html()) between the two lines of code to verify. – Christopher Altman Apr 15 '10 at 20:20
4
divToUpdate.innerHTML =     "";   
Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
plodder
  • 2,304
  • 18
  • 19
3

var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');

That should work just fine.

James Sumners
  • 14,485
  • 10
  • 59
  • 77
2

you should be able to just overwrite it without removing previous data

matei
  • 8,465
  • 1
  • 17
  • 15