My JavaScript code is designed to randomly swap HTML elements like images or paragraphs. The swapping of positions is working, but I've encountered a strange bug that I can't seem to explain. In the example HTML provided, there are only 2 paragraph elements. The swapping works fine for a few times, but then the elements suddenly change positions in an unexpected way.
document.getElementById("pButton").addEventListener("click", () => {
let max = document.querySelectorAll("p").length - 1;
let min = 0;
let x1 = Math.round((Math.random() * (max - min)) + min);
let x2 = Math.round((Math.random() * (max - min)) + min);
while (x1 === x2) {
x2 = Math.round((Math.random() * (max - min)) + min);
}
let tmp1 = document.querySelectorAll("p")[x1];
let tmp2 = document.querySelectorAll("p")[x2];
let tmp1parent = tmp1.parentNode;
let tmp2parent = tmp2.parentNode;
let tmp1Index = 0;
for (let a of tmp1parent.childNodes) {
if (a === tmp1) {
break;
}
tmp1Index += 1;
}
tmp2parent.insertBefore(tmp1, tmp2);
tmp1parent.insertBefore(tmp2, tmp1parent.childNodes[tmp1Index]);
});
<div>
<h1>List</h1>
<p>p1</p>
<ol>
<li>first</li>
<li>second</li>
</ol>
<a>example</a>
<p>p2</p>
<ol>
<li>first</li>
<li>second</li>
<li>third</li>
</ol>
<a>example</a>
</div>
<button id="pButton">BUTTON</button>