簡體   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