I am writting a function to replace the position of some HTML elements in the page. Should be simple and it goes like this :
JavaScript
x
18
18
1
let square = document.getElementById("SquareCharts").children;
2
let testArray = ["A", "b", "c", "d", "E", "f", "g"];
3
4
function Replace(arr, oldPosition, newPosition)
5
{
6
let store;
7
8
store = arr[newPosition];
9
arr[newPosition] = arr[oldPosition];
10
arr[oldPosition] = store;
11
12
return console.log(arr);
13
}
14
15
replace(testArray, 4, 0);
16
replace(square, 4, 0);
17
18
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.
JavaScript
1
23
23
1
let square = document.getElementById("SquareCharts").children;
2
let testArray = ["A", "b", "c", "d", "E", "f", "g"];
3
4
function Replace(arr, oldPosition, newPosition)
5
{
6
let store;
7
8
store = arr[newPosition];
9
arr[newPosition] = arr[oldPosition];
10
arr[oldPosition] = store;
11
12
// clear children
13
square.innerHTML = '';
14
for(const element of arr) {
15
square.append(element);
16
}
17
18
return console.log(arr);
19
}
20
21
replace(testArray, 4, 0);
22
replace(square, 4, 0);
23
document.getElementById("SquareCharts").children
returns a HTMLCollection
. Although it is iterable using a for-loop, it is not an Array.
You can also do:
JavaScript
1
2
1
let square = Array.from(document.getElementById("SquareCharts").children);
2
so that you can get more functionality with Array
‘s built-in methods.