Thursday, March 24, 2011

How do I "refresh" element in DOM?

Hi, I've got an empty DIV element in which I append images by using function createElement("img") and append them with appendChild. So now I've got DIV element full of images.

I would like to use one button to clean this DIV and add new images in it simultaneously. Thanks for your help

From stackoverflow
  • what do you mean by clean? If you just want to empty it, you can do

    document.getElementById('mydiv').innerHTML = '';
    

    And then add on whatever new images you want.

  • Are you just looking for method replaceChild? Or you could remove all child elements before adding new images:

    // assuming yor div is in variable divelement
    while (divelement.firstChild)
      divelement.removeChild(divelement.firstChild);
    
    perfectDay : thanks, i was close, but you helped me.
  • While both setting innerHTML and calling removeChild() in a loop will clear the contents out of the DIV, the innerHTML method is going to be much faster due to the nature of browsers today.

0 comments:

Post a Comment