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#content 元素中的每个子元素,直到只剩下 select 元素。我会说除了第一个子元素之外的每个子元素,但在 Chrome 中似乎有一个我无法控制的 div#content 元素中的不可见文本节点。
或者,如果您有更好的方法在 ajax 加载新内容和删除旧内容的同时将选择元素保留在页面上,我很乐意听到。
最佳答案
删除除第一个 child 以外的所有 child :
while (cntnt.childNodes.length > 1) {
cntnt.removeChild(cntnt.lastChild);
}
您还可以根据要保存的select
的id
进行过滤
while (cntnt.lastChild.id !== 'pSort') {
cntnt.removeChild(cntnt.lastChild);
}
或者您可以获取 pSort
的 innerHTML
并立即将其附加到 ajax 响应中,而无需循环删除元素
cntnt.innerHTML = document.getElementById('pSort').innerHTML + return_data;
关于javascript - 删除除第一个 child 之外的所有子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885788/