I am dynamically creating elements using the document.createElement() method and then setting its attributes using the element.setAttribute() method. It works well and I am able to create elements when I want.
In my code however I want to also remove elements. So I use element.removeChild() method. This removes the element... at least it disappears on the page. But I have found it doesn't always get rid of the all traces of the element.
The elements that I make are all part of a form (they are all input elements). I find that if I refer to the element using document.formName.elementName while it exists then after the element is removed document.formName.elementName is still there, even though the element is removed from the page and removed from the code. If I don't refer to document.formName.elementName then when it is removed it is fine.
I have some sample code of an example of this happening. Does anyone know why or how to get around this?
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function add(){
var element=document.createElement("input");
element.setAttribute("type","text");
element.setAttribute("id","idVal");
element.setAttribute("name","nameVal");
element.setAttribute("value","the value");
document.form1.appendChild(element);
document.getElementsByTagName('textarea')[0].value = document.getElementById('container').innerHTML;
document.getElementById('name').innerHTML = !document.form1['nameVal']==false;
document.getElementById('id').innerHTML = !document.getElementById('idVal')==false;
}
function remove(){
element = document.getElementById('idVal');
document.form1.removeChild(element);
document.getElementsByTagName('textarea')[0].value = document.getElementById('container').innerHTML;
document.getElementById('name').innerHTML = !document.form1['nameVal']==false;
document.getElementById('id').innerHTML = !document.getElementById('idVal')==false;
}
</script>
</head>
<body>
<div id="container">
<form name="form1">
</form>
</div>
<input type="button" value="add textbox" onclick="add()" />
<input type="button" value="remove textbox" onclick="remove()" />
<br /><br />
<textarea style="width:600px; height:100px;"></textarea>
<br /><br />
document.form['nameVal']: <span id="name"></span><br />
document.getElementById('idVal'): <span id="id"></span>
</body>
</html>
|