HTML - attributes vs properties

JavascriptJqueryHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJS-View Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptAnand JhaView Answer on Stackoverflow