Skip to content
GitHub

Working with Attributes

Switch to Zen Mode
// In HTML: <div data-user-id="123" data-role="admin">User</div>
// Get data attribute
const userId = element.getAttribute('data-user-id');
// Using dataset property (camelCase conversion)
const userId = element.dataset.userId;
const role = element.dataset.role;
// Set data attribute
element.dataset.status = 'active';
javascript

const button = document.getElementById("myButton");
// id attribute
button.id = "newId";
console.log(button.className); // Gets class as a string
// class attribute (string)
element.className = 'class1 class2';
// disabled attribute (boolean)
element.disabled = true;
// href for links
anchor.href = 'https://example.com';
// src for images
image.src = 'image.jpg';
// value for form elements
input.value = 'New value';
// checked for checkboxes
checkbox.checked = true;
javascript
  • Retrieves the value of an attribute.
const img = document.querySelector("img");
console.log(img.getAttribute("src")); // "image.jpg"
javascript
  • Sets the value of an attribute.
element.setAttribute('src', 'image.jpg');
javascript
  • Removes an attribute from an element.
const input = document.querySelector("input");
input.removeAttribute("disabled");
javascript

Checks if an element has the specified attribute.

const hasSrc = element.hasAttribute('src');
javascript

Toggles the state of an attribute. If the attribute exists, it is removed; if not, it is added. The force parameter forces the toggle to be true or false.

element.toggleAttribute('disabled');
javascript