What is the difference between properties and attributes in HTML?
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 theid
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 thetype
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">
, thentheInput.getAttribute("type")
gives you"foo"
buttheInput.type
gives you"text"
.In contrast, the
value
property doesn't reflect thevalue
attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, thevalue
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 thevalue
attribute contains the initial text-content of thevalue
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 thevalue
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.
HTML - attributes vs properties
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).
What is the difference between an Attribute and a Property in HTML?
There is an attribute as well as a property called value, for an input element in HTML.
- Value Property - Represents the current value of the input element.
- Value Attribute - Represents the initial value of the input element.
So, in HTML, attributes are defined on HTML elements and are supposed to be the initial values passed to them at the time of creating those elements. Once the browser creates the DOM (a.k.a. after rendering the page), the HTML elements become objects (node objects) and hence, they have properties.
Therefore, in order to change the current value of the input element using Renderer2 of angular, you need to use the setProperty method.
If you use, the setAttribute method, it will change the value only once, that is when you are creating the element. It will not change the current value.
Attribute value VS property value
Quick example of the difference:
jQuery('#something').val()
changes the *.value property.jQuery('#something').attr('value','neValue')
changes the attribute on that component.
There is an important difference between the two. Take a look at this for more info.
What's the difference between jQuery .val() and .attr('value')?
The only thing you have to worry about is whether you are using/assigning/utilizing the correct item - property or attribute
.
Design reason behind the relationship between element's property and its corresponding attribute
You will find the answers buried inside HTML specs. I first want you to have a look at the attributes and properties of the input
element (heading "Content attributes" and "DOM interface") and the section about attribute reflection (first paragraph).
You will notice that all attributes have corresponding properties and manipulating a property will change the attribute it reflects. It is worth noting that:
(1) An attribute could be reflected by a property with a slightly different name. The classical example is the class
attribute which is reflected by className
property and for
attribute which is reflected by htmlFor
property.
(2) Likewise the checked
attribute is reflected by defaultChecked
property whereas the checked
property represents the internal state of the checkbox irrespective of the checked
attribute. This has always caused confusion among programmers (and book authors). The difference is explained at the end of this answer.
(3) Made-up attributes (such as the "book" attribute in your example) will not generate corresponding property and vice-versa. For this purpose the HTML specs describe a mechanism called data attributes and dataset
property.
A related question, if I want to get or set a value on a DOM element,
should I get/set theproperty
or theattribute
?
Depends. For example both of the following produce identical result and HTML:
document.getElementById("div-1").title = "Hello";
document.getElementById("div-1").setAttribute("title") = "Hello";
However, for form elements you should manipulate the state instead of attribute. Suppose you have this HTML markup:
<input type="checkbox" id="checkbox-1">
And you execute either of the following:
document.getElementById("checkbox-1").defaultChecked = true;
document.getElementById("checkbox-1").setAttribute("checked", "checked");
And here is the result:
<input type="checkbox" id="checkbox-1" checked="checked">
But whether the checkbox actually get checked depends on the dirtiness of the control (i.e. if its state was changed at some point). For form elements you would normally manipulate the properties that correspond to the internal state:
document.getElementById("checkbox-1").checked = true;
Why should HTML DOM properties be reflected into HTML DOM attributes as well?
Not all DOM properties map to attributes. The ones that do reflect to and from attributes, do so to maintain parity with the document language — in this case, HTML, which only has a concept of attributes, which as you've correctly pointed out is relied on by Selectors.
If attribute selectors mapped directly to DOM properties without the DOM discriminating between attribute properties and other kinds of properties, then attribute selectors such as the following would match, even though none of these exist as attributes in HTML:
[classList]
[className]
[dataset]
[offsetLeft]
[offsetTop]
[offsetWidth]
[offsetHeight]
... as well as [someAttribute]
matching elements with your non-existent someAttribute
as a property even when you don't reflect it with setAttribute()
.
In fact, this is exactly why label[htmlFor]
incorrectly matches label[for]
elements in Internet Explorer 7, even though the for attribute in HTML is simply called for
, not htmlFor
— the DOM uses htmlFor
to make up for the fact that for
is a reserved word in many languages including JavaScript, the main DOM scripting language, preventing it from being used as a property ident.
Related Topics
Why Does Jquery Only Affect the First Div Element
How to Find the Size of Localstorage
Change Text Color Based on Brightness of the Covered Background Area
Anyone Have a Diff Algorithm for Rendered HTML
How to Disable a Href Link in JavaScript
Vue.Js Get Selected Option on @Change
Dashed Border Animation in CSS3 Animation
Securityerror: the Operation Is Insecure - Window.History.Pushstate()
Html5 - Cross Browser Iframe Postmessage - Child to Parent
Capture Frames from Video with HTML5 and JavaScript
HTML - Attributes VS Properties
Populate One Dropdown List Based on the Selection of Other Dropdown List
How to Get HTML Elements from an Object Tag
Maximum Item Size in Indexeddb
Insert Unicode Character into JavaScript
Html5 Audio Tag on Safari Has a Delay
How to Determine Which HTML Page Element Has Focus
Removing # from Url in Angularjs While Having .Run in Routes