I am moving list elements in a class from one list to another, but I am getting extremely odd behavior.
The relevant Code is found in these functions:
function moveright(){
console.log("things that are selected");
selected=document.getElementsByClassName("Selected");
for (x=0;x<selected.length;x++){
console.log(selected.item(x).innerText);
}
list=document.getElementById("rightlist");
console.log("Moving right");
for (x=0;x<selected.length;x++){
list.appendChild(selected.item(x));
console.log(selected.item(x).innerText);
}
console.log("things that moved right");
for (x=0;x<list.childElementCount;x++){
console.log(list.children.item(x).innerText);
}
}
function select(ele,eve){
if (!(event.shiftKey)){
selected=document.getElementsByClassName("Selected");
for (x=0;x<selected.length;x++){
selected[x].className=selected[x].className.replace(" Selected","");
}
}
if (ele.className.indexOf(" Selected") == -1) {
ele.className=ele.className+" Selected";
}
}
An example of a test element:
<li style="user-select:none" onclick="select(this)" path="./this/is/a/path" class="pft-file ext-txt Selected">test2.txt</li>
rightlist and leftlist are just <ul> elements. When I select three items and execute the moveright function this the console output, which corresponds with what happens on the screen:
things that are selected
test1.txt
test2.txt
test3.txt
Moving right
test2.txt
test1.txt
test3.txt
things that moved right
test1.txt
test3.txt
When I do the same experiment with 2 elements, it still leaves one behind. When I call the function a second time, the last element moves to the rightlist. When I call an identical function to move the elements to the leftlist from the rightlist, it works fine. I'm at my wits end on this one.
EDIT So a little bit of a clue as to what is going on, when I make the list longer, it leaves behind every other item, so any items in the 1,3,5 positions are left and the 0,2,4 positions are taken...
getElementsByClassNamecalls todocument.querySelectorAll(".Selected")instead. This avoids "live list" problems, which can come up with altering the class name of elements and when mutating the DOM structure, both of which you're doing.onclick="select(this)", but the function is defined asfunction select(ele,eve){, but then you're using the globaleventinstead ofeveanyway, so you're going to run into problems there eventually.querySelectoravoided this issue. Thank you for the help. If you put this as an answer I will accept it.querySelectorAllprovides a static list, so it isn't affected by changes made to the DOM. I'll post an answer in a minute.