Reputation: 4302
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?
Upvotes: 2
Views: 2399
Reputation: 322492
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>";
Upvotes: 2
Reputation: 28158
var cell = document.getElementById("cell");
if ( cell.hasChildNodes() )
{
while ( cell.childNodes.length >= 1 )
{
cell.removeChild( cell.firstChild );
}
}
Upvotes: 2
Reputation: 9148
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.
Upvotes: 1
Reputation: 57227
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'))
;
Upvotes: 1
Reputation: 7253
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.
Upvotes: 2