Languages
[Edit]
EN

JavaScript - difference between HTML attributes and properties

0 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you the difference between HTML attributes and DOM properties.

Quick solution:

AttributesProperties
are defined by HTMLare defined by the DOM
their values are constant and can never be changedtheir 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>

 

See also

  1. JavaScript - getAttribute() method example

  2. JavaScript - get attribute name

  3. JavaScript - add element attribute

References

  1. HTMLElement - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join