简体   繁体   中英

How do you clear a <div>s contents with javascript?

I have <div id="editform"></div> . I have certain html currently in it. How do I clear that html and insert completely different html in it?

I tried this but it did not work:

document.getElementById('editform').innerHTML = "";

document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: 

block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";

Any ideas?

var cell = document.getElementById("cell");

if ( cell.hasChildNodes() )
{
    while ( cell.childNodes.length >= 1 )
    {
        cell.removeChild( cell.firstChild );       
    } 
}

I recommend adding HTML to the div using document.createNode(...) and document.appendChild(...) , instead of adding it as innerHTML. Altering innerHTML tends to be buggy.

Your code works fine for me, as long as you remove (or escape) the line breaks from the new HTML string.

Example: http://jsbin.com/olabo4/

So change this:

document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: 

block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";

to this:

document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";

or this:

document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: \
\
block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";

That should work...maybe the problem is somewhere else?

If you want to remove all of the child nodes, try this:

function removeChildren(obj) {
  while(obj.hasChildNodes()) { obj.removeChild(obj.lastChild); }
};

Call it like this:

removeChildren(document.getElementById('editform')) ;

document.getElementById('editform').innerHTML = ""; 

This should work.

and btw, you don't need to escape " in the string, you can use ' inside the string.

Also, to make your life easier, I would recommend some javascript library like JQuery or Mootools, so that your DOM manipulation is easier and cross browser compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM