As title says, whats the difference between elem.is(':checked')
and elem.prop('checked')
.
I personally use elem.is(':checked')
because function is
explains that I am going to return boolean.
When shall I choose one over the other and why?
As title says, whats the difference between elem.is(':checked')
and elem.prop('checked')
.
I personally use elem.is(':checked')
because function is
explains that I am going to return boolean.
When shall I choose one over the other and why?
Answer based on This SO Question.
If you're using 1.6.0 or higher, prop('checked') is the most direct jQuery way. jQuery doesn't have to parse and process a selector to figure out what to do.
Note: The degree to which prop is more direct than is varies by browser. prop isn't just a direct check of a property, it does go through a couple of levels of indirection first; and is isn't necessarily hugely complex: On WebKit browsers, for instance, is can be fairly direct as WebKit provides a function to test whether an element matches a selector, and supports :checked natively; on Firefox (and, I suspect, IE), is results in a huge number of function calls as this seemingly-simple selector works its way through the guts of Sizzle.
Test Result : jQuery prop('checked') vs. is(':checked')
.prop is used to get/set the element's property value. While passing one argument, it will return the property (first argument) value and while passing two arguments, it will set the second argument as value to the first argument (element's property).
Hence, elem.prop('checked')
will return the value of the checked
property. The data type of the value can be anything (boolean/string) based on the property.
If you check elem.prop('type')
, this will return the value of the type
property which is a string
data type and will return checkbox
as output.
.is is used to check whether the element is matching the condition passed in the argument is true/false. Hence, the data type will be always boolean (true/false).
Hence, you can check whether the element is checked (or) not using elem.is(':checked')
. Here, :checked
is called as pseudo
element to check the state
of the element (checked/not checked).
You can also check whether the element is a checkbox or not using elem.is('[type="checkbox"]')
. Here [type="checkbox"]
is used to check the property type
of the element is whether checkbox
or not.