Having trouble moving list items up and down in Javascript

Currently in the process of learning javascript and working on building a simple app. The app consists of an unordered list (ul) with list items (li), each containing two buttons for moving the li up or down.

However, I've encountered an issue where the last item in the list cannot be moved up.

    var ul = document.querySelector('ul');
    
    ul.addEventListener('click', (e) => {
    let clicked = e.target;
    let li= clicked.parentNode;
    let next    = li.nextElementSibling.nextElementSibling;    
     let prev    = li.previousElementSibling;
        
        if (clicked.className === 'down') {
        ul.removeChild(li);
            ul.insertBefore(li, next);
        } else if (clicked.className === 'up') {
        ul.removeChild(li);
        ul.insertBefore(li, prev);
        }
    });
    <ul>
        <li>item1 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item2 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item3 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item4 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item5 <button class="down">Move down</button><button class="up">Move up</button></li>
    </ul>

Check out my jsfiddle to see the code: https://jsfiddle.net/hu13x8w0/3/

I'm seeking guidance on why it's not functioning correctly in those particular cases. Any help is appreciated!

Answer №1

By opening the browser's console (F12 to open Dev Tools in most browsers), you may come across an error message similar to this:

Uncaught TypeError: Cannot read property 'nextElementSibling' of null

This error occurs because the code attempts to access a non-existent next element sibling using the following line:

li.nextElementSibling.nextElementSibling;

In order to prevent this error, it is important to check for null before trying to access the next sibling element:

    var ul = document.querySelector('ul');
    
    ul.addEventListener('click', (e) => {
    let clicked = e.target;
    let li= clicked.parentNode;
    let next    = li.nextElementSibling;               // <-- Code changed
        if (next != null) next = next.nextElementSibling;  // <-- Code inserted
     let prev    = li.previousElementSibling;
        
        if (clicked.className === 'down') {
        ul.insertBefore(li, next);
        } else if (clicked.className === 'up') {
        ul.insertBefore(li, prev);
        }
    });
    <ul>
        <li>item1 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item2 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item3 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item4 <button class="down">Move down</button><button class="up">Move up</button></li>
        <li>item5 <button class="down">Move down</button><button class="up">Move up</button></li>
    </ul>

It's worth noting that there is no need to use .removeChild() in this scenario as .insertBefore() will simply move the element instead of copying it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

What is the best way to test a component that does not properly handle a rejected promise using `wait` in the react-testing-library?

Looking to simulate a failed AJAX request scenario when placing an order on an online shopping store. Additionally, users can choose to subscribe only if the order placement is successful. Currently facing issues with handling Promise rejection in the tes ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

Embed JavaScript code from an ASP.NET webpage into an HTML page on a separate domain

Is it possible to inject JavaScript code from an asp.net page into an HTML page on a different domain, such as http://www.codeproject.com/? How can I achieve this injection from my application? I am currently developing a plugin similar to Pinterest. When ...

Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month? var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set&apos ...

Confirm that one input falls within a specified range of two inputs

I am trying to implement javascript validation for a form with two inputs. Specifically, I want to achieve the following: If a text input is entered and the dropdown remains unselected, the validation should trigger for the text input and the form should ...

Creating a stylish look for a selection of multiple menu options

option:active { color: red; } option:focus { color: green; background: green; } option:checked { color: yellow; background: yellow; } <select multiple> <option>One</option> <option>Two</option> <option&g ...

Enhance the current API functionality by incorporating personalized endpoints

Developing an API for multiple clients presents a unique challenge. While core endpoints like /users are common across all clients, some features may require individual customization. For instance, one client (e.g. "User A") may request a specialized endpo ...

The message I'm attempting to include in the request is not being transmitted along with the request

Currently, I am facing an issue while using Thunder Client to send requests with a POST method. Despite including the body contents and setting the content-type to application/json in the header, whenever I try to access req.body in the request section, ...

Unexpected behavior occurs when using scrollTop to determine the new height after refreshing a div inside a Bootstrap modal

I have included a Bootstrap-based modal that enables users to add and view posts: <div class="modal fade hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="prodCommentModalLabel" aria-hidden="true"> <div class="modal-dialog modal-l ...

Responses were buried beneath the inquiries on the frequently asked questions page

My FAQs page is in pure HTML format. The questions are styled with the css class .pageSubtitle, and the answers have two classes: .p1 and .p2. Here's an example: <p class="pageSubtitle">Which Award should I apply for?</p> <p class="p1" ...

The start-up process of AngularJS applications with Bootstrap

Curious about the predictability of the initialization flow in AngularJS apps? Want to understand the order of execution of different blocks within an HTML document? I came across a question on bootstrapping in Angular JS, but it didn't delve into th ...

When trying to load TinyMCE via AJAX, it fails to appear on the page

My dilemma involves two pages - page1 and page2. On page2, there is a Tinymce initialization setup as follows: $(document).ready(function(){ tinymce.init({ selector: "textarea", theme: "modern" }); }) ...

clicking on a link with the symbol "#" in the href attribute in Firefox prevents the setter

Good morning everyone, It's early Monday morning and I'm having trouble understanding why this particular line works in Internet Explorer but not in Firefox. <a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a> ...

Validate two schemas with Joi conditionally - Schema content is invalid

I am currently working on implementing a conditional schema based on the value of the isCat field in the request body. However, I keep encountering an error that says 'ror [ERR_ASSERTION]: Invalid schema content'. Any ideas on what might be causi ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

Struggling to implement Ajax functionality with JSF on a Tomcat 7.0 server

I am new to Ajax and struggling to get a simple example to work... Here is the javascript code: var xmlRequest; function refreshContent() { if (window.XMLHttpRequest) { xmlRequest = new XMLHttpRequest(); } else { x ...