繁体   English   中英

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

[英]Removing every child element EXCEPT first child?

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元素。 我会说除了第一个之外的每个子元素,但似乎在我无法控制的div#content元素中的Chrome中有一个不可见的文本节点。

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

删除除第一个孩子以外的所有孩子:

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;

你可以这样做:

const firstElementChild = yearRangeToSelector.firstElementChild;
    selectElement.innerHTML = '';
    selectElement.append(firstElementChild);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM