65

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?

Joseph Quinsey
  • 8,830
  • 10
  • 49
  • 71
JS-
  • 937
  • 1
  • 9
  • 12
  • 6
    http://stackoverflow.com/questions/5874652/prop-vs-attr – Satpal Oct 08 '13 at 11:38
  • 5
    @Satpal The linked question is asking the differences between the jQuery functions while this question is asking what the difference is between properties and attributes in HTML. – Trisped Sep 22 '15 at 20:07

2 Answers2

143

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

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 1
    Is there always a property corresponding to every attribute? Is there always an initial 1:1 mapping between the attribute's value and the property's value? – Kevin Wheeler Jul 10 '15 at 22:58
  • 2
    This is a great okram razor answer. Many other answers on other pages go into windbag-philosophy lecture. This is answers simply gives you what you need to be understand. – Phil May 17 '18 at 22:08
4

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

Community
  • 1
  • 1
Anand Jha
  • 9,038
  • 6
  • 21
  • 27