What is different attribute and property in JavaScript and HTML

What is different attribute and property in JavaScript and HTML

2023-03-08
2 min read

Overview

The terms attribute and property is easy to confused in HTML. This article is going to talk about differences between attribute and property together with code example. In addition, You can test all the codes on playground.

Attribute vs Property

First of all, let's see what is Attribute and Property shortly.

Attribute

  • Defined by HTML. (related to HTML)
  • Attribute value can not be changed.
  • Attributes initialize DOM properties when the browser parses the HTML to generate DOM objects for HTML tags.
  • referring to additional information of an object.
  • Attribute update the property synchronously.

Property

  • Defined by the DOM. (related to DOM)
  • Property value can be changed after it's initialized
  • describing the characteristics of an object.
  • Property change does not affect the attribute.

See more details with code

Image that there is following html element in the project.

html
<input id="name-input" type="text" value="name">

In input html element, there are three attributes. id, type and value. Once the browser parses this HTML code, a HTMLInputElement object will be created. JS DOM objects consist of many properties such as accept, checked, classList, className, etc. The properties may be different by DOM objects.

Check "attribute" is existed in element

js
const nameInput = document.querySelector('#name-input')
console.log(nameInput.hasAttribute('type')) // true
console.log(nameInput.hasAttribute('name')) // false

The hasAttribute method in element checks attribute in element whether it's existed. The hasAttribute takes a string parameter and returns string if it's existed.

Get collection of all attributes

js
const nameInput = document.querySelector('#name-input')
console.log(nameInput.attributes) // { 0: Attr { ... }, 1: Attr { ... } }

The attributes property returns collection of all attribute nodes registered to the specified node. It's important that the attributes property is not an array.

Remove "attribute"

js
const nameInput = document.querySelector('#name-input')
nameInput.removeAttribute('value')
console.log(nameInput.value) // undefined

removeAttribute method enable to remove attribute passed by parameter. If you are going to access after removing, that attribute will returns undefined

Access "property" value by "attribute"

js
const nameInput = document.querySelector('#name-input')
console.log(nameInput.value) // "name"
console.log(nameInput.getAttribute('value')) // "name"

The getAttribute method is used to get property in attribute.

Update "property" value with "attribute"

js
const nameInput = document.querySelector('#name-input')
nameInput.value = 'changed'
nameInput.setAttribute('value', 'changed');

Property in attribute can be changed along with the setAttribute method.

Ref

Free open source project made by Youngjin