I’m using a function in a php file to create some “li” and some “span” elements like so:
while($row_quotes=mysql_fetch_array($result_quotes) and $x<10){
$x++;
echo "<li class='citazione'>".$row_quotes['citazione']."</li><span class='citazione_info'>".$row_quotes['personaggio']." - ".$row_quotes['libro']."</span>";
}
These are contained inside “ul id=’quotes_holder'”.
Then I have a javascript function that on a certain call should remove all the created “li” and “span” elements so I thought it would have worked to removing them with the removeChild() method applied on the containing “ul”.
Here’s the javascript function:
function ritorna_filtri(obj, autore){
var index=obj.selectedIndex;
var selected=obj.childNodes[index];
var value= selected.value;
var div=document.getElementById('quotes_holder');
for(l=0;l<div.childNodes.length;l++){
div.removeChild(div.childNodes[l]);
}
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response=xmlhttp.responseText;
jsonObj=eval("("+response+")");
for(i=0;i<jsonObj.libri.length;i++){
var li=document.createElement('li');
var text=document.createTextNode(jsonObj.libri[i].titolo);
li.appendChild(text);
li.setAttribute('class', 'filtro');
div.appendChild(li);
}
}
}
xmlhttp.open("GET","ritorna_filtri.php?filtro="+value+"&autore="+autore,true);
xmlhttp.send();
}
Problem is when the function is executed only the “li” elements are removed, the “span”s are still there.
Your original code does not work since you are looping from
0tochildNodes.length - 1but you are forgetting that once you remove item #0 and increment the counter, item #1 is removed in the next iteration; there will still be an item at #0.The following code can be used to remove an element’s content:
demo
PS: Your HTML markup is invalid.