I have a simple javascript to move an element before and after its siblings. All works fine with moving the element to be inserted before the element before it but when moving to AFTER its next sibling it jumps 2 siblings. If I use [x+1] it doesn’t do anything, I assume because I’m inserting before the next sibling keeping it where it is. What am I doing wrong here? I know I’m missing some simple logic but I can’t figure it out.
//divID variable is the id of the parent element that contains the arrowLeft and arrowRight elements.
let widgBox = document.getElementById('wBox')
let widgBoxArray = widgBox.children
arrowLeft.addEventListener('click',()=>{
//this works as intended
for(let x=0; x<widgBoxArray.length; x++){
if(widgBoxArray[x].id===divID && x !== 0){
widgBox.insertBefore(widgBoxArray[x],widgBoxArray[x-1])
}
}
})
arrowRight.addEventListener('click',()=>{
//this is does not work as intended
for(let x=0; x<widgBoxArray.length; x++){
if(widgBoxArray[x].id===divID && x !== widgBoxArray.length-1){
widgBox.insertBefore(widgBoxArray[x],widgBoxArray[x+2])
}
}
})