javascript - 删除除第一个 child 之外的所有子元素?

标签 javascript html

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);
}

您还可以根据要保存的selectid 进行过滤

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

或者您可以获取 pSortinnerHTML 并立即将其附加到 ajax 响应中,而无需循环删除元素

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

关于javascript - 删除除第一个 child 之外的所有子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885788/

相关文章:

javascript - 格式与多个链接 rel 样式表 CSS (HTML) 混淆

javascript - 多次意外加载 angularjs 会导致奇怪的行为

javascript - 函数在循环后返回对象中的未定义值

javascript - 当光标到达图像时,是否可以使图像随光标移动?

php - 为什么在 Thunderbird 中带有图像附件的 PHP HTML-Mail 渲染不正确?

javascript - 是否可以禁用 jquery 中的单个单选按钮?

javascript - D3.JS 'zoom' 未定义

php - 地址栏中有 "#;"的 firefox

javascript - 移动导航菜单不起作用(HTML、CSS 和 JQuery)

javascript - 通过将函数名存储在变量中来调用js中的函数