Skip to main content

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 property

Now 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:

    javascript
    element.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:

    javascript
    element.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 sync

Some attributes stay in sync with properties (for example, id, class), but not all: for example, value, checked, selected often diverge.


Comparison table

CriterionAttribute (getAttribute)Property (element.prop)
Where it's storedIn the HTML markupIn the DOM object in memory
When it's setWhen the page loadsAt any moment
Changes on interaction?NoYes
Returns a string?Always a stringCan be any type
Examplesid, class, hrefvalue, checked, style

Additionally

Some properties have no attribute at all, for example:

javascript
div.offsetWidth; // property only, it has no HTML attribute

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.