skip to Main Content

I’m trying to figure out how to make a button go to the bottom of the list by clicking on it in JavaScript. I’m a bit of a noob and I didn’t find anything regarding buttons swapping positions.

For example if I click on BTN2 I want the order to be: BTN1, BTN3, BTN4, BTN2

So far I don’t know how to even begin.

<div class="container">
  <div class="attp">
    <p class="textbox">ATTP</p>
    <ul>
      <li><button>BTN1</button></li>
      <li><button>BTN2</button></li>
      <li><button>BTN3</button></li>
      <li><button>BTN4</button></li>
    </ul>
  </div>
</div>

2

Answers


  1. To do what you require you need to attach an event handler to each button. From there you can retrieve the closest li element to the button which was clicked, then move it to the bottom of the ul that contains it by calling append(). Here’s a working example:

    const ul = document.querySelector('.container ul');
    
    document.querySelectorAll('button').forEach(btn => {
      btn.addEventListener('click', e => {
        ul.append(e.target.closest('li'));
      })
    });
    <div class="container">
      <div class="attp">
        <p class="textbox">ATTP</p>
        <ul>
          <li><button>BTN1</button></li>
          <li><button>BTN2</button></li>
          <li><button>BTN3</button></li>
          <li><button>BTN4</button></li>
        </ul>
      </div>
    </div>

    As you’re new to JS here’s some required reading on the functions being used here, as you will need to understand their purpose and usage:

    Login or Signup to reply.
  2. Use Element.closest() and Element.append() methods:

    const attpULs = document.querySelectorAll(".attp ul");
    
    attpULs.forEach((elUL) => {
    
      elUL.addEventListener("click", (evt) => {
        const elBtn = evt.target.closest("button");
        if (!elBtn) return; // Not clicked on a button. Do nothing
        const elLI = elBtn.closest("li"); // Get buton's LI parent
        elUL.append(elLI); // Move button's LI element
      });
      
    });
    <div class="attp">
      <p class="textbox">ATTP</p>
      <ul>
        <li><button type="button">BTN1</button></li>
        <li><button type="button">BTN2</button></li>
        <li><button type="button">BTN3</button></li>
        <li><button type="button">BTN4</button></li>
      </ul>
    </div>

    The above will also work for dynamically generated LI elements since the event is delegated from the parent UL and searches for the button using the Event.target.closest().

    Refer to: MDN web docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search