Organize elements with jQuery, remove, detach, clone, and append without worrying about memory leaks

I am facing a challenge with a parent div that contains approximately 300 child divs, each one containing an image and some text. I have an array with the necessary information to reorder these divs using references.

However, whenever I loop through the array to reorder and move the elements accordingly, I notice severe memory leaks of up to an additional 100MB every time I sort them!

I have attempted a few different approaches but have not found success yet.

$.each(gameArray , function($idx, $itm) { 
    $("#elementid"+ $itm.split('|#|')[0] ).appendTo($("#parent"));
}); 

Another approach:

$.each(gameArray , function($idx, $itm) { 
    var element = $("#elementid"+ $itm.split('|#|')[0] ).detach();
    element.appendTo($("#parent"));
    element = null;
}); 

And another attempt:

$.each(gameArray , function($idx, $itm) { 
    var element = $("#elementid"+ $itm.split('|#|')[0] ).clone(true).remove();
    element.appendTo($("#parent"));
    element = null;
}); 

I have read that detaching the element keeps it in the DOM so there is no need to recreate it when putting it back into the page, thus preventing an increase in memory. However, this does not seem to be working as expected.

Is there something I might be missing? There has to be a way to sort these elements without causing such a significant increase in memory usage.

All the examples I have come across involve ordered lists with only about 10 list elements, making it hard to notice any memory increase.

Answer ā„–1

When facing performance issues during heavy (DOM) operations, it is advisable to ditch jQuery completely and revert back to using vanilla JavaScript, especially when the alternative without jQuery is compatible with all modern browsers.

var fragment = document.createDocumentFragment(); // Temporary storage
for (var $idx=0, len = gameArray.length; $idx<len; $idx++) {
    var $itm = $gameArray[$idx];
    fragment.appendChild(
        document.getElementById("elementid" + $itm.split('|#|', 1)[0] )
    );
}
// Append all items to parent
document.getElementById('parent').appendChild(fragment);

The methods used in this code snippet are:

Answer ā„–2

Consider implementing a solution similar to the following example:

HTML:

<div id="parent">
    <div id="0">0</div>
    <div id="1">1</div>
    <div id="2">2</div>
    <div id="3">3</div>
    <div id="4">4</div>
    <div id="5">5</div>
    <div id="6">6</div>
    <div id="7">7</div>
    <div id="8">8</div>
    <div id="9">9</div>
</div>

Javascript:

var games = [ 4, 3, 0, 2, 5, 1, 6, 9, 7, 8 ]; // desired sort order

var $parent = $('#parent');
var $children = $parent.children('div');

$children.detach().sort(function(a,b){
    var aId = parseInt( $(a).attr('id'), 10 );
    var bId = parseInt( $(b).attr('id'), 10 )
    return games.indexOf(aId) > games.indexOf(bId);
});

$parent.append($children);

This process involves detaching the children elements, sorting them based on a predefined order, and then reappending them back to the parent element without directly modifying the DOM structure during the sorting operation.

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 with socket malfunctioning when integrated with express

Iā€™m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

SignalR's postback interrupts the functionality of jQuery actions

On my screen, I have a widget that updates data and changes its class based on server-side interactions. It also responds to mouse clicks. To notify multiple clients of updates simultaneously, I'm using SignalR. The problem arises when I wrap everythi ...

Tips on assigning a data-id attribute

After a click event, I am attempting to dynamically set the data-id and/or value of a span using my JavaScript file. <span id="test"></span> Here is an example of the JavaScript code: nextLink: function(event) { $('#test').val ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Using a function as a prop in Vue js to retrieve data from an API

I am facing an issue with a component that I want to decouple from the data fetching implementation. My goal is to be able to pass a data fetching callback as a prop. The reason for this is so that I can easily mock the data fetching process in storybook. ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

Choose the elements that do not possess a specific class as their ancestor

I'm facing an issue with my HTML code. Here's what it looks like: <div class="asd"> <audio src="..."> </div> <audio src="..."> <audio src="..."> <audio src="..."> My goal is to select all of the audio el ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Unusual behavior observed with ES5 filter functionality in Node.js

My goal is to use ES5 : filter to refine the data provided below. { "EmailAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167c797356736e777b667a73e98175d3faf7">[email protected]</a> ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

The alert box in Javascript appears before the execution of the statement preceding it

I am encountering a peculiar issue, which is not unexpected considering my limited experience with JavaScript. I am currently working on developing a basic high-low card game where two cards are drawn and the highest card wins. Below you can find the code ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

What is the method to render certain text as bold using a json string?

I need assistance with concatenating two strings in react while ensuring that the first string is displayed in bold, while the second one remains unchanged. The first string I want to emphasize is stored in a JSON file, and the second string comes from an ...