Working with Attributes
When working with HTML elements in JavaScript, you’ll often need to check, change, or remove their attributes. Attributes are those extra bits inside HTML tags—like id
, class
, href
, or data-*
—that give elements their properties and behavior. JavaScript gives you simple methods to handle these, and once you get the hang of them, you’ll be tweaking attributes like a pro.
.getAttribute('attributeName'): Grab the value of an attribute
The .getAttribute()
method is used to get the value of a specified attribute on an HTML element.
It returns the attribute value as a string (or null if element does not have an attribute)
Syntax
element.getAttribute('AttributeName');
- element: The DOM element you want to inspect.
- attributeName: The name of the attribute whose value you want to get (as a string).
Example
<button id="myButton" data-action="submit">Click Me</button>
const button = document.getElementById('myButton');
// Get the value of 'data-action'
const action = button.getAttribute('data-action');
console.log(action); // Output: "submit"
// Common mistake: assuming direct property access works for custom attributes
console.log(button.dataAction); // Output: undefined (because 'data-action' isn't a direct property)
Another Example
<img src=”1.png”>
const img = document.querySelector('img');
const altText = img.getAttribute('alt');
if (altText === null) {
console.log('No alt attribute found');
} else {
console.log(`Alt text: ${altText}`);
}
When to Use .getAttribute()
- When you need to access custom attributes (especially data-* attributes).
- When you want the literal attribute value as specified in HTML.
- When working with attributes that don't have corresponding DOM properties.
Why this matters: Custom attributes (like data-*) must use getAttribute(). Standard ones (like id) can use direct properties (button.id).
.setAttribute('attributeName', 'newValue')
Use this when you want to change or add an attribute. Super useful in things like changing image sources dynamically, updating ARIA roles, or adding target="_blank"
to links you’ve just inserted.
Syntax
element.setAttribute(attributeName, value);
element:
The DOM element you want to modify.attributeName:
The name of the attribute you want to set (as a string).value:
The value you want to assign to the attribute.
Examples
1. Setting a simple attribute
const link = document.querySelector('a');
link.setAttribute('href', 'https://www.example.com');
2. Adding a class
const div = document.getElementById('myDiv');
div.setAttribute('class', 'highlight');
3. Setting data attributes
const item = document.querySelector('.item');
item.setAttribute('data-price', '19.99');
If the attribute doesn’t exist, setAttribute()
creates it for you. No extra steps. Clean and simple.
Real talk: Don’t rely on this for styling. Back when I was hacking together my first gallery, I tried changing a class with setAttribute('class', 'new-class')
. It worked… until I needed to add multiple classes dynamically. That’s when I met classList
. We’ll get to that.
.removeAttribute('attributeName'): Delete an attribute completely
Sometimes you just need to strip an attribute away. removeAttribute()
wipes it clean. Calling img.removeAttribute('alt') removes the alt text—handy if you’re dynamically adjusting images.
But be careful: removing required attributes (like type on an <input>) can break things.
Syntax
element.removeAttribute(attributeName);
- attributeName (String): The name of the attribute you want to remove
Examples
Basic Usage
// Remove the 'disabled' attribute from a button
const button = document.getElementById('myButton');
button.removeAttribute('disabled');
Removing Multiple Attributes
const link = document.querySelector('a');
link.removeAttribute('target'); // Removes target="_blank" etc.
link.removeAttribute('title'); // Removes any tooltip text
Common Use Cases
- Removing disabled state from form elements.
- Removing inline styles.
- Removing custom data attributes.
- Removing custom data attributes.
Direct Property Access: The shortcut that isn’t always what it seems
A lot of the time, attributes have direct property equivalents. For example:
const input = document.querySelector('input');
console.log(input.value); // Gets the current value (not the HTML one)
Here’s the tricky part: attributes and properties aren't always in sync. Take input.value
vs input.getAttribute('value')
. The property reflects the live state of the element, while the attribute shows what’s in the HTML.
input.value = 'New Value';
console.log(input.getAttribute('value')); // Still the original!
This disconnect has bitten me more than once. I thought setting .value
would also change the attribute—it doesn’t. So if you’re using JavaScript to persist form states or rebuild DOM nodes, know which one you’re using.
Same goes for things like element.checked
, element.selected
, or element.disabled
. When in doubt, inspect both. Or just read this MDN doc that saved my sanity more than once.
Quick Check-In on the Course Project
Let’s wire this into our course project. Say we’re building a form where users can add links. Here's a snippet that reads and updates a link's href
and title
:
const userLink = document.querySelector('#userLink');
userLink.setAttribute('href', 'https://jsbites.info');
userLink.setAttribute('title', 'Check out JSBites!');
And if we want to clean it up later:
userLink.removeAttribute('title');
Later in the course, we’ll dynamically build elements using this approach. Getting this right now sets us up for way less pain.