I’m making Search Box and it has histories. When clicking the histories I want to remove clicked element and add it again as a first child. However, I have a problem.
For example:
if I click on the Number 4 element firstly everything is okay.
My 4. element becomes Number 1 element and number 3 element becomes number 4 element.
But if I click Number 4 element again, it behaves 3. element clicked. Maybe for this project, I can change the method but I want to understand why there is a problem.
My Elements:
<div id="histories">
<div class="history-content">9</div>
<div class="history-content">8</div>
<div class="history-content">7</div>
<div class="history-content">6</div>
<div class="history-content">5</div>
<div class="history-content">4</div>
<div class="history-content">3</div>
<div class="history-content">2</div>
<div class="history-content">1</div>
</div>
Javascript:
// HistoryContent is my element I want to change the order.
let HistoryContent = document.getElementsByClassName("history-content");
//historiesID is Parent Child(container) of HistoryContent
const historiesID = document.getElementById("histories");
document.addEventListener("DOMContentLoaded", (event) => {
let click = 0;
for(let i = 0; i<HistoryContent.length; i++) {
HistoryContent[i].addEventListener("click", function(event) {
// Thera are somethings I don't want to click so I attached the if condition
if(event.target !== document.getElementsByClassName("history-icon") && document.getElementsByClassName("xmark-svg")) {
let copy = HistoryContent[i];
historiesID.insertBefore(copy, historiesID.firstElementChild);
// Debugging
click++;
console.log("Index number of your clicked element:",i);
console.log("That's your",click+"th click.");
}
});
}
});
I clicked 3 times at index number 3 and Debugging:
Index number of your clicked element: 3
That's your 1th click.
Index number of your clicked element: 2
That's your 2th click.
Index number of your clicked element: 2
That's your 3th click.