除第一个子元素外,如何删除所有子元素?

8
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中似乎有一个不可见的文本节点,我无法控制。

或者如果您有更好的方法,在ajax加载新内容并删除旧内容的同时保留选择元素在页面上,我很乐意听取建议。


目标字符串的确切条件是什么?它必须在数组中吗? - rdonatoiop
已更新原帖,并尽量提供了所有可用的代码。似乎我有一个不好的习惯,总是没有贴足够的代码。 - Azrael
我想,Ricardo,只要在ajax调用执行时保持选择器#pSort元素在页面上,它不一定需要在数组中。 - Azrael
4个回答

35

仅保留第一个子元素:

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

您还可以按照要保存的 selectid 进行过滤。

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

或者你可以直接获取 pSortinnerHTML,将其与 ajax 响应一起追加,而无需循环删除元素。

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

1
如果childNodes始终>1会怎样? - beautifulcoder
2
直到循环删除所有元素,只剩下一个为止! - kavun
1
考虑到数组中的每个迭代都更新其lastChild,听起来是这样的。 - rdonatoiop
2
如果您只想针对元素而不是空格,请使用children。 - PussInBoots
很好的发现,@PussInBoots - 如果第一个元素是空格,我的方法可能不会达到你想要的效果。 - kavun

4
您可以这样做:
const firstElementChild = yearRangeToSelector.firstElementChild;
    selectElement.innerHTML = '';
    selectElement.append(firstElementChild);

1

0
当 (cntnt.childNodes.length > 1) { cntnt.children(cntnt.lastChild); // 这个只获取顶层子节点 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接