Which jQuery methods should be avoided in favour of built-in methods / properties?
Example:
$('#el').each(function(){
// this.id vs $(this).attr('id');
// this.checked vs $(this).is(':checked');
});;
Which jQuery methods should be avoided in favour of built-in methods / properties?
Example:
$('#el').each(function(){
// this.id vs $(this).attr('id');
// this.checked vs $(this).is(':checked');
});;
I use the direct javascript property like this.id
in these cases:
I use the jQuery access method when:
For example: str = $(elem).html()
doesn't really have any advantages over str = elem.innerHTML
, but $(elem).html(str)
does have some advantages over elem.innerHTML = str;
because the jQuery method will clean up the objects that are being removed more completely than the innerHTML way.
This is a broad question but here's a couple of guidelines that I think are useful. You can/should use native js methods when:
The first condition should be true in any case :) The others can combine or go separately. I understand that they are all debatable and can provoke long talks on philosophy but I think they are good starting points and summarize lots of cases.
But the bottom line is - if you don't have a reason to avoid library methods, use them!
Most DOM properties are problem-free in all major browsers. For the two examples you mention (id
and checked
), the DOM properties are 100% reliable and should be used in preference to the jQuery equivalent for reliability, performance and readability.
The same goes for all properties corresponding to boolean attributes: readonly
, disabled
, selected
are common ones. Here are some more. className
is also 100% solid. For other properties and attributes, it's up to you. Using a library like jQuery may be the best approach for these if you're unsure and can afford to lose some performance (usually the case).
Stack Overflow regular Andy Earnshaw has blogged about this: http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element