删除每个子元素除了第一个孩子吗?

问题描述:

function sortPosts() { 
var pSort = document.getElementById('pSort').selectedIndex; 
var pstSort = document.getElementById('pSort').options; 
var sorted = pstSort[pSort].value; 
var hr = new XMLHttpRequest(); 
var url = "..."; 
var vars = "sort="+sorted; 
hr.open("POST", url, true); 
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
hr.onreadystatechange = function() { 
    if (hr.readyState === 4 && hr.status === 200) { 
     var return_data = hr.responseText; 
     var cntnt = document.getElementById('content'); 
     while ((cntnt.lastChild !== ' 
     <select id="pSort"> 
      <option value="all" selected="true">All Posts</option> 
      <option value="friends">Friends\' Posts</option> 
      <option value="following">Following\'s Posts</option></select>' && cntnt.childNodes.length !== 1) || (cntnt.firstChild != '<select id="pSort"><option value="all" selected="true">All Posts</option><option value="friends">Friends\' Posts</option><option value="following">Following\'s Posts</option></select>' && cntnt.childNodes.length != 1)) { 
      cntnt.removeChild(cntnt.lastChild); 
     } 
     document.getElementById('content').innerHTML += return_data; 
     document.getElementById('content').style.opacity = '1.0'; 
    } 
} 
hr.send(vars); 
document.getElementById('content').style.opacity = "0.5"; 

}删除每个子元素除了第一个孩子吗?

我需要删除在div#内容元素的每个子元素,直到只有选择的元素仍然存在。我会说除了第一个以外的每个子元素,但似乎Chrome中有一个无法控制的div内容元素中的无形文本节点。

或者,如果您有更好的方法来保持页面上的select元素,而Ajax加载新内容并删除旧内容,我很乐意听到它。

+2

我们需要看到更多的代码,我怀疑比较是不是你想要的...... – elclanrs

+2

请让你的代码可读。 – wvdz

+0

涉及目标字符串的确切条件是什么?它必须在数组中吗? – rdonatoiop

要删除所有,但第一个孩子:

while (cntnt.childNodes.length > 1) { 
    cntnt.removeChild(cntnt.lastChild); 
} 

您还可以通过的idselect要保存

while (cntnt.lastChild.id !== 'pSort') { 
    cntnt.removeChild(cntnt.lastChild); 
} 

或者你可以只得到pSortinnerHTML和过滤器立即附加ajax响应,无需循环移除元素

cntnt.innerHTML = document.getElementById('pSort').innerHTML + return_data; 
+1

如果cildNodes始终> 1,该怎么办? – beautifulcoder

+2

直到循环移除除一个之外的所有东西! – kavun

+1

考虑到数组中的每一次迭代都更新其lastChild,听起来就像它。 – rdonatoiop