Reputation: 23
Note: I do not know JQuery, only Vanilla JavaScript.
Good evening,
I cannot retrieve the updated Index of a class element after reordering the class element using the insertBefore() function.
Example: Elements A, B, C with indexes 0, 1, 2 when rearranged: C, A, B will have indexes 2, 0, 1 instead of 0, 1, 2.
Here is my code that I have used for testing. You can click on the individual elements, the button reorder will move the last element before the first, and the index results can be viewed in the Console Log:
let container = document.getElementById('container');
let items = document.querySelectorAll('.items');
items.forEach((row, index) => {
row.addEventListener('click', () => {
console.log(index);
});
});
let reorder = document.getElementById('reorder').addEventListener('click', () => {
container.insertBefore(container.children[4], container.children[0]);
});
#container {
border: 2px solid black;
display: inline-block;
position: relative;
}
.items {
border: 2px solid red;
margin: 2px;
width: 20px;
}
<div id="container">
<div class="items">0</div>
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
</div>
<button id="reorder">ReOrder</button>
Upvotes: 1
Views: 79
Reputation: 50854
Your current solution doesn't work as index
is a part of a closure that is initially set when your for
loop firsts adds the event listeners. You could find the index of the element you clicked on by searching for it amongst the children by using .indexOf()
. You'll first need to convert the children to an array (this is done below using the spread syntax ...
) as it is a HTMLCollection, which doesn't have an indexOf method:
let container = document.getElementById('container');
let items = document.querySelectorAll('.items');
items.forEach((row, index) => {
row.addEventListener('click', (event) => {
console.log([...container.children].indexOf(row));
});
});
let reorder = document.getElementById('reorder').addEventListener('click', () => {
container.insertBefore(container.children[4], container.children[0]);
});
#container {
border: 2px solid black;
display: inline-block;
position: relative;
}
.items {
border: 2px solid red;
margin: 2px;
width: 20px;
}
<div id="container">
<div class="items">0</div>
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
</div>
<button id="reorder">ReOrder</button>
Upvotes: 1