I am writting a function to replace the position of some HTML elements in the page. Should be simple and it goes like this :
let square = document.getElementById("SquareCharts").children; let testArray = ["A", "b", "c", "d", "E", "f", "g"]; function Replace(arr, oldPosition, newPosition) { let store; store = arr[newPosition]; arr[newPosition] = arr[oldPosition]; arr[oldPosition] = store; return console.log(arr); } replace(testArray, 4, 0); replace(square, 4, 0);
It works with testArray but it doesn’t seem to have any effect on the HTML elements order. Why and what can I do to change the original DOM?
Advertisement
Answer
You need to clear the element’s current children then append them again.
let square = document.getElementById("SquareCharts").children; let testArray = ["A", "b", "c", "d", "E", "f", "g"]; function Replace(arr, oldPosition, newPosition) { let store; store = arr[newPosition]; arr[newPosition] = arr[oldPosition]; arr[oldPosition] = store; // clear children square.innerHTML = ''; for(const element of arr) { square.append(element); } return console.log(arr); } replace(testArray, 4, 0); replace(square, 4, 0);
document.getElementById("SquareCharts").children
returns a HTMLCollection
. Although it is iterable using a for-loop, it is not an Array.
You can also do:
let square = Array.from(document.getElementById("SquareCharts").children);
so that you can get more functionality with Array
‘s built-in methods.