Optimizing jQuery Selector

I have five forms that has tons of JavaScript data validations and AJAX calls. Worst, it is looping intensive. As a result, it was too slow. At first I thought it was just because I have so many fields on the form. However, as the need to optimized it, I’ve read some jQuery selector optimization technique.

I have a lot of looping structure which uses this kind of selector in jQuery:

	var x =0;
	var val = null;
	
	workComCdChange.prev = $("[id=Work_Com_Cd]").val();
	tariffCdChange.prev = $("[id=Tariff_Cd]").val();
	
	for (x=0; x<totalSubforms; x++)
	{
		if (typeof VAR_NOEDIT == "undefined")
		{
			val = $("[id=Number_" + x + "]").val();

		//the rest of the codes

I though using that kind of select will use the JavaScript’s native getElementByID since I’ve specified it as ID by instead, it will match tags by matching its attribute which is ID and not via DOM id.

To optimize it, I tried replacing it with the # selector.

	var x =0;
	var val = null;
	
	workComCdChange.prev = $("#Work_Com_Cd").val();
	tariffCdChange.prev = $("#Tariff_Cd").val();
	
	for (x=0; x<totalSubforms; x++)
	{
		if (typeof VAR_NOEDIT == "undefined")
		{
			val = $("#Number_" + x).val();

		//the rest of the codes

After that, I’ve noticed an increased performance by 70%!

I will never use attribute as selector again when all we need is unique id.

This entry was posted in JavaScript and tagged , , , , , , , , . Bookmark the permalink.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>