Working with Attributes
// In HTML: <div data-user-id="123" data-role="admin">User</div>
// Get data attributeconst userId = element.getAttribute('data-user-id');
// Using dataset property (camelCase conversion)const userId = element.dataset.userId;const role = element.dataset.role;
// Set data attributeelement.dataset.status = 'active';javascript
const button = document.getElementById("myButton");// id attributebutton.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 linksanchor.href = 'https://example.com';// src for imagesimage.src = 'image.jpg';// value for form elementsinput.value = 'New value';// checked for checkboxescheckbox.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