Given jQuery's philosophy of write less, do more, I'm always surprised when I see this:
$(this).prop('checked')
… instead of this:
this.checked
Looking at the latest jQuery source, prop() provides convenience for these two gotchas:
$(elem).prop('for') is equivalent to elem.htmlFor.$(elem).prop('class') is equivalent to elem.className.It also normalizes tabIndex to:
prop() is certainly useful for setting properties for multiple elements at once, and for chaining properties on a single element.
But is there any advantage (other than idiomatic) to use prop() to set or retrieve a single property on a single element except when normalizing tabIndex – specifically when you have a reference to the element (such as this in a callback)?
.prop as a getter has no real advantage, in fact, it is less performant than directly accessing the property.
The real utility of .prop is when used as a setter.
If you read the DOC, there is 3 way of setting something with .prop.
The first way has no advantage for a single element(except maybe if there is compatibility issue).
In fact this.check = true; is the same as $(this).prop('checked', true), but faster.
If you have a set of element though, there is an advantage. You don't have to manually loop all elements, jQuery does it for you.
The second way is useful when you have multiple properties to change. Instead of listing every properties you want to change like that :
this.prop1=true;
this.prop2=true;
this.prop3=true;
this.prop4=true;
You can pass an object like that :
$(this).prop({
prop1 : true,
prop2 : true,
prop3 : true,
prop4 : true
});
The third way is in my opinion my favorite one. Using a callback function allow you to set every element individually on a set of condition. The callback receive 2 arguments: the index and the old value.
A good example of the use of a function is to reverse the state of every checkbox:
$('checkbox').prop('checked', function(_, old){
return !old;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With