Attributes vs properties of a DOM element
The main difference
- An attribute is what is written in the HTML code.
- A property is what is stored in the DOM object in JavaScript memory.
Put simply:
An attribute is what the browser read from the HTML. A property is the element's current state in JS.
Example
javascript
<input id="name" value="Alex">javascript
const input = document.querySelector('#name');
console.log(input.getAttribute('value')); // "Alex", from the HTML
console.log(input.value); // "Alex", the current propertyNow the user types a new value into the field, for example "Max":
javascript
console.log(input.getAttribute('value')); // still "Alex" (the attribute does not change)
console.log(input.value); // "Max" (the property changed)Bottom line: an attribute is the "starting value", a property is the "current state".
Attributes are part of the HTML
-
Stored in the source code.
-
Can be read and changed using:
javascriptelement.getAttribute(name); element.setAttribute(name, value); element.hasAttribute(name); element.removeAttribute(name);
Properties are part of the DOM's JS object
-
They exist as regular object properties:
javascriptelement.value element.checked element.id element.className -
Changing a property may not change the attribute (and vice versa).
Examples where the difference is visible
Example 1: checked
javascript
<input type="checkbox" checked>javascript
const box = document.querySelector('input');
console.log(box.getAttribute('checked')); // "": the attribute is present
console.log(box.checked); // true: the property is active
box.checked = false;
console.log(box.getAttribute('checked')); // still "" (the attribute did not disappear)
console.log(box.checked); // false (the state changed)Example 2: class and className
javascript
<div class="item"></div>javascript
const el = document.querySelector('.item');
console.log(el.getAttribute('class')); // "item"
console.log(el.className); // "item"
el.className = 'product';
console.log(el.getAttribute('class')); // "product", here it's in syncSome attributes stay in sync with properties (for example, id, class),
but not all: for example, value, checked, selected often diverge.
Comparison table
| Criterion | Attribute (getAttribute) | Property (element.prop) |
|---|---|---|
| Where it's stored | In the HTML markup | In the DOM object in memory |
| When it's set | When the page loads | At any moment |
| Changes on interaction? | No | Yes |
| Returns a string? | Always a string | Can be any type |
| Examples | id, class, href | value, checked, style |
Additionally
Some properties have no attribute at all, for example:
javascript
div.offsetWidth; // property only, it has no HTML attributeShort Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.