In the following script all works fine except the “Remove all items”.
It adds and removes individual elements fine, but when I call the dropElems() function
it removes up to the last 2. If I click it again, it removes only one.
Finally, pressing one more time does remove all.
My question is why. ?
I’m calling the same function to remove one element multiple times
to remove all the elements, but it seems to stop short of the actual desired action.
[code]
<html>
<body>
<script type=”text/javascript”>
var elemCount = 0;
function pushElem() {
elemCount++;
var m = “New Element “+elemCount;
var n = document.createElement(“li”);
n.appendChild(document.createTextNode(m));
document.getElementById(“myList”).appendChild(n);
}
function popElem() {
if (elemCount > 0) {
elemCount–;
document.getElementById(‘myList’).removeChild(document.getElementById(‘myList’).lastChild);
}
}
function dropElems() {
var sel = document.getElementById(‘myList’).getElementsByTagName(‘li’);
alert(sel.length); // for testing purposes only
for (var i=0; i<sel.length; i++) { popElem(); }
}
window.onload = function() {
for (var i=0; i<5; i++) { pushElem(); } // simulated drop-down creation
}
</script>
<input type=”button” value=”Add list item” onClick=”pushElem();”>
<input type=”button” value=”Remove added items” onClick=”popElem();”>
<input type=”button” value=”Remove all items” onClick=”dropElems();”>
<ul id=”myList”></ul>
</body>
</html>