Is id
an attribute or property of HTML?
should I do $('#selector').attr('id');
or $('#selector').prop('id');
I've read many articles and am still confused.
Could someone please explain to me what the differences between attributes & properties in HTML/JS are in very simple language?
Attributes are additional information which we can put in the HTML to initialize certain DOM properties. Properties are formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser.
An attribute is a quality or character ascribed to or considered to belong to, or be inherent in, a person or thing. A property is a quality or characteristic belonging to a person or thing, with its original use implying ownership, and also either being essential or special.
prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. So use prop!
Using the same attribute name twice in a tag is considered an internal parse error. It would cause your document to fail validation, if that's something you're worried about. However, it's important to understand that HTML 5 defines an expected result even for cases where you have a "parse error".
Attributes are defined by HTML. Properties (on DOM elements) are defined by DOM (and also HTML 5 which blurs the boundary between markup and DOM).
Some HTML attributes have 1:1 mapping onto properties. id
is one example of such.
Sometimes the names are different. The class
attribute maps onto the className
property, and the value
attribute maps on to the defaultValue
property (while the value
property has no corresponding attribute).
When I originally wrote this answer, I thought there were attributes without a 1:1 mapping to a property. With this update, I can no longer think of any (and have made corrections for the above examples).
Yes, attr is meant for html attributes as they are strictly defined. prop is for properties.
So for instance, say you have a node elem with class "something" (raw element not jQuery object). elem.className is the property, but is where the attribute resides. Changing the class attribute also changes the property automatically and vise versa.
Currently, attr is jumbled and confusing because it has tried to the job of both functions and there are many bugs because of that. The introduction of jQuery.fn.prop will solve several blockers, separate code as it should have been separated from the beginning, and give developers faster functions to do what they expect them to do.
Let me make up a percentage for a sec and say that from my experience in the support IRC and reading other's code, 95% of the use cases for attr will not have to switch to prop.
See More
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