MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • Attribute methods
  • element.attributes
  • Attribute-property synchronization
  • DOM properties are typed
  • The data-* attributes
  • Summary
  1. 2nd Month
  2. Week 6
  3. DOM (Document Object Model)
  4. Working with Attributes

Understanding Relationships Between HTML Attributes & DOM Object’s Properties

PreviousWorking with AttributesNextsetAttribute()

Last updated 1 year ago

When the web browser , it generates the corresponding DOM objects based on the DOM nodes of the document.

For example, if a page contains the following input element:

<input type="text" id="username">Code language: JavaScript (javascript)

The web browser will generate an HTMLInputElement object.

The input element has two attributes:

  • The type attribute with the value text.

  • The id attribute with the value username.

The generated HTMLInputElement object will have the corresponding properties:

  • The input.type with the value text.

  • The input.id with the value username.

In other words, the web browser will automatically convert attributes of HTML elements to properties of DOM objects.

However, the web browser only converts the standard attributes to the DOM object’s properties. The standard attributes of an element are listed on the element’s specification.

Attribute-property mapping is not always one-to-one. For example:

<input type="text" id="username" secured="true">Code language: JavaScript (javascript)

In this example, the secured is a non-standard attribute:

let input = document.querySelector('#username');
console.log(input.secured); // undefinedCode language: JavaScript (javascript)

Attribute methods

To access both standard and non-standard attributes, you use the following methods:

element.attributes

The element.attributes property provides a live collection of attributes available on a specific element. For example:

let input = document.querySelector('#username');

for(let attr of input.attributes) {
    console.log(`${attr.name} = ${attr.value}` )  
}Code language: JavaScript (javascript)

Output:

type = text
id = username
secure = trueCode language: JavaScript (javascript)

Attribute-property synchronization

When a standard attribute changes, the corresponding property is auto-updated with some exceptions and vice versa.

Suppose that you have the following input element:

<input type="text" id="username" tabindex="1">Code language: JavaScript (javascript)

The following example illustrates the change of the tabindex attribute is propagated to the tabIndex property and vice versa:

let input = document.querySelector('#username');

// attribute -> property
input.setAttribute('tabindex', 2);
console.log(input.tabIndex);  // 2


// property -> attribute
input.tabIndex = 3;
console.log(input.getAttribute('tabIndex')); // 3Code language: JavaScript (javascript)

The following example shows when the value attribute changes, it reflects in the value property, but not the other way around:

let input = document.querySelector('#username');

// attribute -> property: OK
input.setAttribute('value','guest');
console.log(input.value);  // guest


// property -> attribute: doesn't change
input.value = 'admin';
console.log(input.getAttribute('value')); // guestCode language: JavaScript (javascript)

DOM properties are typed

The value of an attribute is always a string. However, when the attribute is converted to the property of a DOM object, the property value can be a string, a boolean, an object, etc.

The following checkbox element has the checked attribute. When the checked attribute is converted to the property, it is a boolean value:

<input type="checkbox" id="chkAccept" checked> Accept

let checkbox = document.querySelector('#chkAccept');
console.log(checkbox.checked); // trueCode language: JavaScript (javascript)

The following shows an input element with the style attribute:

<input type="password" id="password" style="color:red;with:100%">Code language: JavaScript (javascript)

The style attribute is a string while the style property is an object:

let input = document.querySelector('#password');

let styleAttr = input.getAttribute('style');
console.log(styleAttr);

console.dir(input.style);Code language: JavaScript (javascript)

Output:

[object CSSStyleDeclaration]Code language: JavaScript (javascript)

The data-* attributes

If you want to add a custom attribute to an element, you should prefix it with the data- e.g., data-secured because all attributes start with data- are reserved for the developer’s uses.

To access data-* attributes, you can use the dataset property. For example, we have the following div element with custom attributes:

<div id="main" data-progress="pending" data-value="10%"></div>Code language: JavaScript (javascript)

The following shows how to access the data-* attributes via the dataset property:

let bar = document.querySelector('#main');
console.log(bar.dataset);Code language: JavaScript (javascript)

Output:

[object DOMStringMap] {
    progress: "pending",
    value: "10%"
}Code language: JavaScript (javascript)

Summary

  • Attributes are specified in HTML elements.

  • Properties are specified DOM objects.

  • Attributes are converted to properties respectively.

  • Use the element.attributes property to access standard and custom attributes of an element.

  • Use the element.dataset property to access the data-* attributes.

element.getAttribute(name) –

element.setAttribute(name, value) –

element.hasAttribute(name) –

element.removeAttribute(name) –

Note that element.attributes is a NamedNodeMap, not an , therefore, it has no Array’s methods.

2️⃣
loads an HTML page
get the attribute value
set the value for the attribute
check for the existence of an attribute
remove the attribute
Array