Home > Blockchain >  Rearrange children orger in Javascript doesn't work multiple times
Rearrange children orger in Javascript doesn't work multiple times

Time:03-24

I've got the following code to move the childs order in an element. When I click once, it works fine, but when I click multiple times, it only works every 2nd or 3rd time.

const prevP = () => {
    const pList = document.getElementById("project-list")

    const firstProject = pList.firstChild;

    const lastProject = pList.lastChild;

    pList.insertBefore(lastProject, firstProject);
}

const nextP = () => {
    console.log("next");
    const pList = document.getElementById("project-list")

    const firstProject = pList.firstChild;

    let lastProject = pList.lastChild;

    pList.insertBefore(firstProject, lastProject);
}
<span  onclick="prevP()"
            >navigate_before</span
          >
          <div  id="project-list">
            <div >
              <img href="protfolio" alt="" />
              <p>My Portfolio 1</p>
            </div>
            <div >
              <img href="protfolio" alt="" />
              <p>My Portfolio 2</p>
            </div>
            <div >
              <img href="protfolio" alt="" />
              <p>My Portfolio 3</p>
            </div>
            <div >
              <img href="protfolio" alt="" />
              <p>My Portfolio 4</p>
            </div>
            <div >
              <img href="protfolio" alt="" />
              <p>My Portfolio 5</p>
            </div>
          </div>
          <span  onclick="nextP()"
            >navigate_next</span
          >

I also realised that sometimes the code messes up the order of the elements when using both buttons, and I have no idea why this is happening

CodePudding user response:

The cause of that behaviour is that you use firstChild and lastChild. These may select text nodes with just some white space. Change these to firstElementChild and lastElementChild.

Secondly, the "Next" action should not insert the first element before the last element, but after it. For that you can use the method appendChild:

    pList.appendChild(firstProject);
  • Related