Is there a way to relocate an li element to the end of a ul list?

I've been struggling to figure out how to move an li element to the bottom of a ul in JavaScript. I looked at various solutions on Stack Overflow, such as Move the first four list items to the end of the list and Move items in Ul Li up and down, but none of them worked for my specific case. I even attempted removing the li and adding it back later, but had trouble with the onclick functionality.

Below is the code snippet for the ul:

<ul class="role_box_roles" id="rbroles">
    <li class="role_box_role" style="border-color: rgb(255, 0, 0);">
        <button class="role_remove_button" type="button" style="background-color: rgb(255, 0, 0);">-</button>
        <span>Staff</span>
    </li>
    <li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>

The desired li element to be kept at the bottom is the one identified by the "plusbutton" id. (Whenever a new item is added to the ul, it should appear below the "plusbutton" li.)

Here's the add_option function that adds a new option to the ul:

function add_option(optionname) {
    var listItem = document.createElement("li");
    var removeButton = document.createElement("button");
    var optionSpan = document.createElement("span");

    listItem.className = "role_box_role";
    listItem.style = "border-color: rgb(255, 0, 0);";

    //removeButton.type = "button";
    removeButton.innerText = "-";
    removeButton.className = "role_remove_button";
    removeButton.style = "background-color: rgb(255, 0, 0);";

    optionSpan.innerText = optionname;

    listUl = document.getElementById("rbroles");
    listUl.appendChild(listItem);
    listItem.appendChild(removeButton);
    listItem.appendChild(optionSpan);
}

Answer №1

You have the option to utilize the before() method in order to achieve the same result by simply referencing the specific node (li) you wish to add before.

Check out this live demonstration:

function insert_option(optionname) {
  var listItem = document.createElement("li");
  var removeButton = document.createElement("button");
  var optionSpan = document.createElement("span");

  listItem.className = "role_box_role";
  listItem.style = "border-color: rgb(255, 0, 0);";

  //removeButton.type = "button";
  removeButton.innerText = "-";
  removeButton.className = "role_remove_button";
  removeButton.style = "background-color: rgb(255, 0, 0);";

  optionSpan.innerText = optionname;
  listItem.appendChild(removeButton);
  listItem.appendChild(optionSpan);
 
  // Grab reference node
  var referenceNode = document.querySelector('#plusbutton');

  // Insert the new node before the reference node
  referenceNode.before(listItem);
}
<ul class="role_box_roles" id="rbroles">
  <li class="role_box_role" style="border-color: rgb(255, 0, 0);">
    <button class="role_remove_button" type="button" style="background-color: rgb(255, 0, 0);">-</button>
    <span>Staff</span>
  </li>
  <li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>


<button onclick="insert_option('Blah')">
  Add
</button>

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

Is it possible to utilize relative paths with webpack dev server in React JS projects?

While running the development server on localhost:3000 using npm run start, everything functions as expected. I am utilizing react-scripts and have not ejected the react app. Currently, my goal is to configure the dev server behind a reverse proxy so that ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Struggling to concatenate array dynamically in Vue using ajax request

I am working on a Vue instance that fetches objects from a REST endpoint and showcases them on a web page. Most parts of the functionality work smoothly like filtering, however, there is an issue when attempting to add new objects by requesting a new "page ...

What causes the discrepancy in calculating marginTop on a desktop browser compared to a mobile browser?

In the top screenshot, you can see a representation of my Pixel 6XL connected to my laptop in USB debug mode. The checkered area represents the URL bar on the Chrome browser displayed on my Pixel device. Below that, the second screenshot shows the view fr ...

What is the best way to display the ID value as a variable in a bootstrap modal dialog?

I originally thought figuring this out would be a breeze, but it's proving to be quite the challenge. After scouring for solutions without success, I find myself stuck. There's a list of dynamically generated buttons with unique id values that I ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

What's the Catch with Vue's Named Slots?

When working with Named Slots in Vue (using the older, more verbose API for component slots), if there is a reusable component with a template structured like this: <template> <div v-for="field in formFields"> <slot name="`${field.key}_P ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

Display an empty string when a value is NULL using jQuery's .append() function

To set an HTML value using the .append() function, I need to include AJAX data values. If the data set contains a null value, it will show as 'null' in the UI. I want to remove that 'null' and display it as blank. However, I can't ...

React js experiences a crash when it attempts to re-render with a different number of child elements

When working with react.js, I came across the need for a component that renders a 'tr' with either one or two 'td' elements, depending on its property. Here is an example: var Item = React.createClass({ content: function() { ...

Securing your folders with Next Auth middleware

I am currently developing a NextJS application and have implemented routers at pages/dashboard/* that I need to secure. My goal is to restrict access to these routes only to authenticated users. I am utilizing Prisma for data management, with Google as the ...

Failed to access the 'totalQty' property as it is undefined

I have developed a cart object that can hold products in a shopping cart. The issue arises when an item is undefined before it gets added to the cart. How can I ensure that the cart is defined even when it's empty during the session? I am using ejs. ...

Experiencing issues with exporting <SVG> file due to corruption

I received some downvotes on my previous post, and I'm not sure why. My question was clear, and I provided a lot of information. Let's give it another shot. My issue is with exporting <SVG> files from an HTML document. When I try to open t ...

Update the state by utilizing the File's onLoad function

I've been facing some challenges while trying to set the state using FileReader's onLoad function. My objective is to display multiple images and update the state accordingly. Despite extensively researching various stackoverflow threads and mak ...

State changes are not being properly reflected in the function within Next.Js

I am currently working on a functional component that displays an array of products. The products are received as props and the component utilizes the useEffect and useState hooks to manage its state. One of the functionalities I am trying to implement is ...

Customize the appearance of radio buttons in HTML by removing the bullets

Is there a way for a specific form component to function as radio buttons, with only one option selectable at a time, without displaying the actual radio bullets? I am looking for alternative presentation methods like highlighting the selected option or ...

Retrieve the pdf document from the server's response

Currently, I am working on a project where I am using PHP Laravel to create a docx file, converting it to PDF, and saving it in a public server folder. Afterwards, I send the file as a response to the client. On the client side, I am attempting to downloa ...

What is the jquery alternative to the PHP 'if IP equals' condition?

I am curious to know if the following PHP 'if' conditions can be achieved in jquery or JavaScript, with a preference for jquery. if ($_SERVER['REMOTE_ADDR'] != '123.99.55.616') { // public doingness } if ($ ...