Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this).prop('property') vs. this.property

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:

  1. $(elem).prop('for') is equivalent to elem.htmlFor.
  2. $(elem).prop('class') is equivalent to elem.className.

It also normalizes tabIndex to:

  • 0 for tabbable elements without a tab index.
  • -1 for non-tabbable elements.

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)?

like image 310
Rick Hitchcock Avatar asked Oct 30 '25 21:10

Rick Hitchcock


1 Answers

.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.


.prop(prop, value)

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.


.prop({prop : value[, prop : value, ...]});

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
});

.prop(prop, callback)

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;
});
like image 84
Karl-André Gagnon Avatar answered Nov 02 '25 10:11

Karl-André Gagnon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!