EN
JavaScript - difference between HTML attributes and properties
0
points
In this article, we would like to show you the difference between HTML attributes and DOM properties.
Quick solution:
| Attributes | Properties |
|---|---|
| are defined by HTML | are defined by the DOM |
| their values are constant and can never be changed | their values are variables that can be changed |
| they initialize the DOM properties, and after the initialization, their work is complete |
Practical example
In the example below, we create an element that has two attributes: id and class.
<div id="element-id" class="visible">Example text...</div>
Once the browser parses the code, an HTMLElement object will be created and it will contain many properties (such as accessKey, offsetTop, offsetLeft etc.).
When a DOM node is created for an HTML element, many of its properties relate to attributes with the same name (like id) or similar names (e.g class - attribute, className - property) but it is not a one-to-one relationship.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="element-id" class="visible">Example text...</div>
<script>
var element = document.querySelector('#element-id');
console.log(element.id); // Output: element-id
console.log(element.class); // Output: undefined (because there's no class property)
console.log(element.className); // Output: visible (value initialized with class attribute)
</script>
</body>
</html>