Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new list? Essentially, only the re-ordered list should be displayed on the page, not the original list.

var ul = document.querySelector('ul');

const order = [3,1,2,0];
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>

Answer №1

  • To transform your array of indexes into a DocumentFragment, you can either use the Array spread syntax or the Array reduce method.
  • Once you have your iterable ready, you can use the .append() method to add it to the same parent UL element.

const orderList = [3, 1, 2, 0];

const ul = document.querySelector('#list');
const li = ul.querySelectorAll('li'); 
ul.append(...orderList.map(i => li[i]));
<ul id="list">
  <li>0</li>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Comparing the performance between using DocumentFragment and Array destructuring with Spread syntax, the latter method is faster based on this benchmark test: this benchmark test

const liReordered = orderList.reduce((DF, i) => (DF.append(li[i]), DF), new DocumentFragment());
ul.append(liReordered);

One advantage of preserving events when reinserting elements using these methods is that any event already assigned to those LI elements will not be lost. This is different from using innerHTML or insertAdjacentHTML etc.

const orderList = [3, 1, 2, 0];

const ul = document.querySelector('#list');
const li = ul.querySelectorAll('li'); 

li.forEach(el => el.addEventListener("click", () => {
  console.log("Events are preserved!");
}));

ul.append(...orderList.map(i => li[i]));
<ul id="list">
  <li>0 CLICK ME</li>
  <li>1 CLICK ME</li>
  <li>2 CLICK ME</li>
  <li>3 CLICK ME</li>
</ul>

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

Tips on retrieving data in AJAX from various fields upon button click

Description: I am looking to implement functionality where a user clicks on a button within a while loop to trigger an AJAX call that retrieves and sends the value of both the button and an input field to PHP. If there are any issues in my code, please ...

Problem occurs when tab links vanish after clicking on another part of the website

Exploring the world of Javascript as a newcomer has been quite an adventure, but I've encountered a hurdle with tab links on my website. Everything seems to be working fine – the links cycle through and display the correct content. However, when it ...

Fade background position rollover effect

I'm facing a challenge with animating my background image using background positioning. The CSS is functioning correctly, but when I attempted to enhance it by adding jQuery for a rollover effect, the animation isn't working as expected. Can anyo ...

Achieve a sliding effect between two divs using CSS only

I'm trying to create a design with 2 divs that are the same size. The first one is visible by default, while the second one is hidden initially. My goal is to achieve an effect where when you hover over the first div, the second one slides upward and ...

The speed of the Ionic app is disappointingly sluggish on devices, causing significant delays

After testing my app in Ionic Lab, it runs smoothly. However, when I create the apk file and install it on my device, the performance is very slow. There are delays in clicking on buttons, pushing pages, opening modals, and closing modals. It seems like t ...

What are the steps to resolving an issue with importing a css file in next.js?

Error: ./node_modules/quill-emoji/dist/quill-emoji.css ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need a suitable loader for handling this file type, as there are currently no configured loaders to process it. ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

What is the best way to close a popup window?

Is there a way to close my popup? function hidePopup(){ document.getElementById("popup-1").classList.remove("active"); } @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap'); .popup .overlay{ positio ...

Error in CSS styling affecting image display on responsive website

My CSS seems to have a bug when it comes to responsive pages with images. Take a look at the demo: https://jsfiddle.net/xr4getom/ If you resize the window on this example, you'll notice that a dark background (#222) appears intermittently. Is there ...

Trapping an iframe refresh event using jQuery

I am trying to dynamically load an iframe using jQuery. Here is my code: jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){ // do something when loaded }).prependTo("#myDiv"); Now, I need to capture th ...

Updating Ajax Data within a LoopExplanation: In this scenario, we

Here is my AJAX function: function updatePrice(id, prid, divid, key, name) { $.ajax({ type: "POST", data: "aid=" + id + "&prid=" + prid, url: '<?php echo base_url('grocery/onchange')?>&a ...

Updating the Ajax Url dynamically while scrolling

I am trying to update the Ajax URL dynamically, and here is my progress so far: var size=1; var from = 1; window.addEventListener('mousewheel', function(e){ if(e.wheelDelta<0 && from<5){ from++; } else if(e.whe ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...

Learn how to apply formatting to all textboxes on an ASP.NET website using CSS without having to set the CSS class property for each individual textbox

I am currently developing a website using Asp.Net. I am looking for a way to customize the font, color, and background color of all the textboxes on my site using CSS. However, I would like to avoid having to assign a "cssclass" property to each individua ...

Discovering the initial vacant row within an HTML table with Javascript

Below is a snippet of code that generates a table with 6 rows. The last two rows remain empty. The JavaScript logic in the code correctly determines and displays the total number of rows in the table. I'm currently looking for a way to identify the ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Issue with Material UI: An invalid value was detected for the select component, even though the value is within the available options

I am facing an issue with a dropdown list component using material UI. The dropdown is populated by an API call and displays a list of departments with their corresponding IDs and names. Upon selecting a record from a table, the department name associated ...

Using Jquery to dynamically adjust select options based on the value of another select option

My goal is to create a short form where each select box dynamically populates the next one. The options for the first select box are hardcoded in the body, while the subsequent options are defined as an HTML string in a variable corresponding to the value ...

Updating elements with jQuery each/ajax during a loop may not take effect

My goal is to refresh a list after receiving data from an ajax call. The process looks like this: $.ajaxSetup({ async: false }); $.ajax(jsonUrl, { dataType: "json", success: function(data) { $.each(data.list, function(k,v) { ...

Can animations be stacked in a queue while using velocity.js?

I'm currently tackling a project involving a push menu. When the content div slides over, the menu buttons come in with a slight animation as they appear on the screen. However, if the user rapidly opens and closes the menu multiple times, the items o ...