578

After the changes made in jQuery 1.6.1, I have been trying to define the difference between properties and attributes in HTML.

Looking at the list on the jQuery 1.6.1 release notes (near the bottom), it seems one can classify HTML properties and attributes as follows:

  • Properties: All which either has a boolean value or that is UA calculated such as selectedIndex.

  • Attributes: 'Attributes' that can be added to a HTML element which is neither boolean nor containing a UA generated value.

Thoughts?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
schalkneethling
  • 6,327
  • 3
  • 21
  • 20
  • 6
    Possible duplicate of [.prop() vs .attr()](http://stackoverflow.com/questions/5874652/prop-vs-attr) – Naftali Sep 06 '16 at 13:48

7 Answers7

1153

When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element:

<input type="text" value="Name:">

has 2 attributes (type and value).

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:

<input id="the-input" type="text" value="Name:">

the corresponding DOM node will have id,type, and value properties (among others):

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn't modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn't reflect the value attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
    

    The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

    So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue property, which is a pure reflection of the value attribute:

    theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
    

There are several properties that directly reflect their attribute (rel, id), some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. The spec covers the various kinds of reflection.

user664833
  • 18,397
  • 19
  • 91
  • 140
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 1
    Hey Sime, I am guessing this is pretty ambiguous, especially if you have a look over here: http://www.w3.org/TR/html4/index/attributes.html, and there is no clear cut answer. One basically needs to follow what is stated in the summary on the jQuery blog and even then, the one will map to the other and work in both instances with a slight performance hit should you incorrectly use prop when you need to use attr – schalkneethling May 15 '11 at 17:44
  • 7
    @oss Your link refers to a list of HTML attributes. That list is not ambiguous - those are attributes. – Šime Vidas May 15 '11 at 19:22
  • are there some documents about the relation ? @ŠimeVidas – SKing7 Aug 19 '15 at 12:02
  • 3
    Where could I find a complete list of attributes to properties (like `for` -> `htmlFor`) and similarly a list of properties that take their initial value from an attribute, yet do not reflect it (`input.value`). I expect this would be somewhere in the source of a library like https://github.com/Matt-Esch/virtual-dom but it's not really documented. – sstur Jul 02 '16 at 00:40
  • `htmlFor` and `className` are the only ones whose names are different from their corresponding attributes, I think. Not sure about there being a complete list; maybe we could make one, if you give me a good use case for it :) – Šime Vidas Jul 02 '16 at 02:17
  • @ŠimeVidas I need such a list because I need to output all properties and attributes of an element and I don't want any duplicates which might confuse whoever's getting that list (I need the properties to write rules for identifying elements on the page). – Dina Aug 17 '16 at 07:18
  • great explanation but you didn't mention about `setAttribute` and how it works when no attribute was initially set. `` has no `value` attribute, but both `getAttribute('value')` and `input.value` will return empty string. Furthermore `setAttribute('value', newVal')` (and subsequent) will change both attribute and `value`/`defaultValue` properties. But if you now set `input.value` as a empty string (which already is), subsequent `setAttribute` calls will affect only attribute and `defaultValue` property, `value` property stays the same. – cimak Jun 25 '19 at 11:45
  • @cimak It seems that form fields can be in an “initial” state: As long as the field isn’t edited — either directly on the page, or by setting its `.value` property — the `setAttribute` call will effectively re-initialize the element. Interesting behavior. – Šime Vidas Jun 25 '19 at 14:03
  • @ŠimeVidas Do you know a good resource (book, tutorial, or online guide) to learn more about parsing, the DOM, and the basics of HTML rendering in a browser? – Pim Nov 19 '19 at 19:30
  • 1
    @Pim I haven’t read it myself, but this 4-part article series seems like a great resource: https://twitter.com/addyosmani/status/1082177515618295808 – Šime Vidas Nov 20 '19 at 15:11
  • I think the attributes can have any user defined random ones where as the properties can't. Please correct if i am wrong. – raj240 May 29 '20 at 19:39
  • When we use the word "object" in DOM, what programming language savesthat object? Javascript or the programming language which created the browser? – Einsamer Sep 03 '21 at 15:40
  • Amazing answer, here is my understanding and hopefully it helps: think of attributes on the html elements as **config** information. When browser parses DOM, for each element it reads, it constructs corresponding internal representation of the element based on attributes ("config") specified and some other settings. This way, attributes **initialize** states of properties. Properties can freely change their states later, and such change would also be reflected via element rendering on the page. – torez233 Nov 06 '21 at 03:30
125

After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.

HTML attribute vs. DOM property


Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.

  • Some HTML attributes don't have corresponding properties. colspan is one example.

  • Some DOM properties don't have corresponding attributes. textContent is one example.

  • Many HTML attributes appear to map to properties ... but not in the way you might think!

That last category is confusing until you grasp this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob">, it creates a corresponding DOM node with a value property initialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute: input.getAttribute('value') returns "Bob".

The HTML attribute value specifies the initial value; the DOM value property is the current value.


The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When you add the disabled attribute, its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button>.

Setting the button's disabled property disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

zeroG
  • 320
  • 2
  • 12
subtleseeker
  • 4,415
  • 5
  • 29
  • 41
  • This example is not right: the `colspan` attribute has the `colSpan` property. ... So, which attribute does not have a related property now? – Robert Siemer Feb 15 '20 at 05:24
51

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

sibidiba
  • 6,270
  • 7
  • 40
  • 50
  • 24
    This is not an answer but I'm agree with you; it's totally insane. – Samuel May 14 '13 at 13:22
  • Yes this concept sucks and should not been standardised so badly. This was one of the cases (like innerHTML for example) that was good in old IE and should have been adopted by the standards. Properties and attributes were synchronised wherever possible, even custom attributes, making very nice readable js dot syntax. HTML5 makes custom HTML tags first class citizens, custom attributes should also be. This feature being removed since old IE is still a real issue - we are only just now seeing a lot of corporates traditionally stuck with IE for old systems now finding them broken in IE10. – mike nelson Aug 07 '13 at 07:02
  • 55
    It's not insane. You've misunderstood. The `checked` attribute is represented by the `defaultChecked` property (likewise for a text input the `value` attribute is represented by the `defaultValue` property). A second property, `checked`, is required to represent whether the checkbox is checked because this is an intrinsic part of a checkbox's functionality: it is interactive and can be changed (and reset to the default, if a form reset button is present) by the user, in a way that another attribute such as `id` is not. It's nothing to do with the fact that it's a boolean attribute. – Tim Down Oct 23 '13 at 10:03
  • 3
    @TimDown -- Thanks. That actually got me over the WTF? hump. – pedz Jul 08 '14 at 02:23
  • 14
    @TimDown I still feel it is "insane" because any logical approach would make the property name and the attribute name match, or at least not have an attribute name and property name match that are not related (i.e. the checked attribute refers to the defaultChecked property while the checked property is unrelated). In fact, the logical approach that everyone assumes is the case at the start would be to not separate the attributes and properties at all. Attributes should not be immutable, but should always reflect the property values. There shouldn't be a distinction between the two. – dallin Aug 05 '15 at 23:18
  • 3
    It's not insane if you understand why it is forged this way. It was made like this because `forms` have a reset method and that reset method need to read the original data from the HTML attribute. – Ahmad Alfy Oct 28 '18 at 18:53
  • And also, of course, there is a standard attribute named "property" – William Entriken May 21 '20 at 18:48
  • I agree it is insane in hindsight. As they say, hindsight is 20/20. Back when forms were introduced, that made perfect sense. Nowadays we think about the web in a different, more consistent way, and all these inconsistencies are bugging us a lot. – Gianluca Ghettini Jul 12 '21 at 14:16
18

Difference HTML properties and attributes:

Let's first look at the definitions of these words before evaluating what the difference is in HTML:

English definition:

  • Attributes are referring to additional information of an object.
  • Properties are describing the characteristics of an object.

In HTML context:

When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:

  • 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. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered

It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.

Furthermore have different DOM elements different properties. For example, an <input> element has a value property which is not present on a <div> property.

Example:

Let's take the following HTML document:

 <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">  <!-- charset is a attribute -->
  <meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
  <title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>

Then we inspect the <div>, in the JS console:

 console.dir(document.getElementById('foo'));

We see the following DOM properties (chrome devtools, not all properties shown):

html properties and attributes

  • We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
  • We can see that the class attribute in the HTML has no corresponding class property (class is reserved keyword in JS). But actually 2 properties, classList and className.
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • 2
    This answer is excellent because it shows _examples_, without which the distinction between attributes and properties is easy to miss. – ProfDFrancis Mar 23 '23 at 08:47
11

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

Community
  • 1
  • 1
  • Hey Daniel, I did read that. Just seems there is know clear cut definition to separate the two, as some of what Sime mentions below can also be added to the HTML element, for example alt. Will continue to read some of the HTML spec and see if there is indeed a way to clearly distinguish the two in practice. – schalkneethling May 15 '11 at 14:08
  • 5
    That document relates to SVG not HTML. – Luzado Feb 05 '18 at 14:25
5

Update to my answer this a citation from https://angular.io/guide/binding-syntax

HTML attributes and DOM properties

Attributes initialize DOM properties and you can configure them to modify an element's behavior, but Properties are features of DOM nodes.

  • A few HTML attributes have 1:1 mapping to properties; for example, id.

  • Some HTML attributes don't have corresponding properties; for example, aria-*.

  • Some DOM properties don't have corresponding attributes; for example, textContent.

Remember that HTML attributes and DOM properties are different things, even when they have the same name.

Example 1: an When the browser renders , it creates a corresponding DOM node with a value property and initializes that value to "Sarah".

<input type="text" value="Sarah">

When the user enters Sally into the , the DOM element value property becomes Sally. However, if you look at the HTML attribute value using input.getAttribute('value'), you can see that the attribute remains unchanged—it returns "Sarah".

The HTML attribute value specifies the initial value; the DOM value property is the current value.

Example 2: a disabled button A button's disabled property is false by default so the button is enabled.

When you add the disabled attribute, you are initializing the button's disabled property to true which disables the button.

<button disabled>Test Button</button>

Adding and removing the disabled attribute disables and enables the button. However, the value of the attribute is irrelevant, which is why you cannot enable a button by writing Still Disabled.

To control the state of the button, set the disabled property instead.

Property and attribute comparison Though you could technically set the [attr.disabled] attribute binding, the values are different in that the property binding must be a boolean value, while its corresponding attribute binding relies on whether the value is null or not. Consider the following:

<input [disabled]="condition ? true : false">
<input [attr.disabled]="condition ? 'disabled' : null">

The first line, which uses the disabled property, uses a boolean value. The second line, which uses the disabled attribute checks for null.

Generally, use property binding over attribute binding as a boolean value is easy to read, the syntax is shorter, and a property is more performant.

mkamal
  • 199
  • 2
  • 6
  • 1
    This is partially a copy paste from [www.coursehero.com](https://www.coursehero.com/file/puustd/When-the-user-enters-Sally-into-the-input-the-DOM-element-value-property/). If you copy and paste answers,, so let the people know the source of the original answer. – B001ᛦ May 21 '21 at 23:17
  • 1
    Wow! If I hadn't read your comment I would have thought that the answer is really good. Thanks :) – Vijay Dev May 22 '21 at 05:06
  • 1
    sorry guys, forgot to mention the answer is from https://angular.io/guide/binding-syntax – mkamal May 23 '21 at 22:25
2

Attribute: Attributes are defined by HTML and are used to customize a tag.

Properties: HTML DOM properties are values (of HTML Elements) that you can set or change.

So, the main differences between attributes and properties are:

  • Attributes are defined by HTML, but properties are defined by the DOM.

  • The attribute’s main role is to initializes the DOM properties. So, once the DOM initialization complete, the attributes job is done.

samnoon
  • 1,340
  • 2
  • 13
  • 23
  • Attributes aren't constant, they can be updated in many cases e.g. `inputElement.setAttribute('maxlength', 2)` – Drenai Apr 09 '23 at 11:31
  • 1
    In some cases it is necessary to use the attribute and not the prop after initialized. If you have a HTML progress bar that is initialized with a specific value but later you want to change it to indeterminate then the only way is to removeAttribute, using .value = null resets to 0 but doesnt force into the indeterminate state. tl;dr it isn't always black and white – Mâtt Frëëman Aug 02 '23 at 10:12