An easy way to manipulate data off dom using jQuery

Posted at March 05, 2012

When you’re working with javascript you need to take the execution speed into account since its all being processed on the client. There are lots of best practices when it comes to working with websites. You should for example always minify and concatenate your scripts, and make good use of closures and avoid polluting the global scope.

Another thing you should keep in mind is to keep as much big changes to the DOM offside the DOM. This is because every time you change something the browser needs to calculate a lot of things again (repaints and reflows) and more importantly, every query to the DOM is very slow.

If you need to change a part of the page you need to do this of course, and you can’t get around it when you want to animate stuff (when CSS3 is no possibility). But when you want to update a large amount of data on the page (at the same time) it’s best to temporary take that part off the dom, update everything you want and put it back on the dom. This way you don’t have a reflow / repaint on every manipulation.

This can easily be achieved by using jQuery.

//instead of doing:
$('#container').find('p').each(function(i) {
   $(this).append('this is p ' + i);
});

Keep in mind that you need to know the parent element to which you want to append (or prepend) it later on. Notice how I chain it all together, by using .appendTo instead of .append we can use the current working set we have already instead of saving it into a variable.

Using this method to sort an jQuery set

Imagine you have an html div like so:

<div id='container'>
   <p data-number='5'>a</p>
   <p data-number='2'>b</p>
   <p data-number='6'>c</p>
   <p data-number='3'>d</p>
   <p data-number='1'>e</p>
   <p data-number='4'>f</p>
</div>

And you want to sort them based on the data-number attribute. You can easily select the set, take it off dom and use javascript array functions on the set.

function numberSort(a, b) {
   return $(a).data('number') > $(b).data('number') ? 1 : -1;
}

The result will be:

<div id='container'>
   <p data-number='1'>e</p>
   <p data-number='2'>b</p>
   <p data-number='3'>d</p>
   <p data-number='4'>f</p>
   <p data-number='5'>a</p>
   <p data-number='6'>c</p>
</div>

Posted at March 05, 2012, under jQuery.