Synchronizing Data

Every DOM node has built-in JavaScript properties, but it also has HTML attributes (the things you write inside the HTML tag like id, src, or class).

1. Properties

These are standard JavaScript variables inside the DOM object. You can even invent your own: document.body.myData = 5.

2. Attributes

These are exactly what is written in the HTML file. To work with them, we use specific methods:

  • hasAttribute(name): Checks if the attribute exists.
  • getAttribute(name): Reads the value of the attribute.
  • setAttribute(name, value): Writes a new value to the attribute.
  • removeAttribute(name): Deletes the attribute entirely.

Let's check if the body tag has an 'id' attribute:

JS Console

Type: document.body.hasAttribute('id')

Now, let's forcefully add a custom attribute to the body:

JS Console

Type: document.body.setAttribute('hello', 'world')

Important

Synchronization: Usually, when a standard HTML attribute changes (like id), the corresponding JavaScript property also changes automatically. But there are exceptions! For example, the value attribute of an input field synchronizes from the HTML attribute to the JS property, but changing the JS property does NOT update the HTML attribute.

Tip

If you want to store custom data in HTML, always use the prefix data-* (like data-user-id="123"). In JavaScript, you can easily access all these data attributes via the dataset property!