There are a few issues with your approach, and your JavaScript console will typically assist in debugging most of these.
First of all, consider the objects newdiv
and orgdiv
. Inside your else
block, you reference both of these, but they are not declared or initialized anywhere. There is a declaration in your if
block, but of course that doesn't get run the second time this method is called. When the else
block is executing, the if
block is ignored altogether.
So you need to correct your object references:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId"); // assuming div has an ID
...
Then of course, in your if
block, you will initialize newdiv
correctly since it doesn't exist yet.
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
Finally, when removing the element, you're incorrectly referencing the parent as a property of the child (newdiv.orgdiv.removeChild(newdiv);
). Instead, just access the parent directly:
orgdiv.removeChild(newdiv);
So your final solution becomes:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId");
if (str.length != 0) {
if (count == 0) {
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
orgdiv.appendChild(newdiv);
count = 1;
alert("firstif");
} else alert("first if else");
} else {
alert(str);
count = 0;
alert(count);
orgdiv.removeChild(newdiv);
}
}
See also Node.removeChild MDN docs