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 |
In the example below, we create an element that has two attributes: id
and class
.
xxxxxxxxxx
1
<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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element-id" class="visible">Example text...</div>
5
<script>
6
7
var element = document.querySelector('#element-id');
8
9
console.log(element.id); // Output: element-id
10
11
console.log(element.class); // Output: undefined (because there's no class property)
12
console.log(element.className); // Output: visible (value initialized with class attribute)
13
14
</script>
15
</body>
16
</html>