DOM Manipulation: Attributes (getAttribute, setAttribute, etc.)
HTML elements often have attributes that provide additional information about the element or configure its behavior (e.g., src for an image, href for a link, class for styling, id for unique identification). In JavaScript, you can read, modify, add, and remove these attributes dynamically using specific DOM methods or, for some common attributes, direct property access.
Understanding attribute manipulation is key to creating dynamic and responsive web content.
1. What are HTML Attributes?
Attributes are defined directly within the opening tag of an HTML element as name-value pairs.
<img src="image.jpg" alt="Description" class="thumbnail" data-id="123">
In this example, src, alt, class, and data-id are attributes.
2. Accessing Attribute Values
You can get an attribute's value using the getAttribute() method or, for some common attributes, by directly accessing the element's property.
a) element.getAttribute(attributeName)
- Purpose: The standard way to retrieve the value of any attribute (custom or standard) as a string.
- Returns: The attribute's value as a string, or
nullif the attribute doesn't exist on the element. - Key Point: Always returns the value as it is written in the HTML source.
b) Direct Property Access (element.propertyName)
- Purpose: Many standard HTML attributes have corresponding DOM properties that allow direct access. This is often more convenient and can return values in their processed JavaScript type (e.g., boolean for
checked, absolute URL forhref). - Common Mappings:
idattribute ➡️element.idpropertysrcattribute ➡️element.srcpropertyhrefattribute ➡️element.hrefpropertyvalueattribute (for inputs) ➡️element.valuepropertyclassattribute ➡️element.classNameproperty (note theNamesuffix to avoid conflict with JSclasskeyword)
- Returns: The property's value, which might be a string, boolean, or other data type.
3. Modifying Attribute Values
Attributes can be changed using setAttribute() or by assigning a new value to the corresponding direct property.
a) element.setAttribute(attributeName, value)
- Purpose: The standard way to set or update the value of any attribute (custom or standard). If the attribute doesn't exist, it will be added.
- Returns:
undefined.
b) Direct Property Assignment (element.propertyName = value)
- Purpose: For common attributes, you can directly assign a new value to their corresponding DOM property. This is often more readable and sometimes handles type conversions automatically.
4. Checking and Removing Attributes
a) element.hasAttribute(attributeName)
- Purpose: Checks if an element has a specific attribute.
- Returns:
trueif the attribute exists,falseotherwise.
b) element.removeAttribute(attributeName)
- Purpose: Removes a specified attribute from an element.
- Returns:
undefined.
5. Summary and Best Practices
getAttribute()/setAttribute()/hasAttribute()/removeAttribute():- Use these methods for:
- Custom attributes (e.g.,
data-*attributes). - Attributes that don't have direct DOM properties.
- When you need the exact string value as written in HTML (e.g., a relative
hrefvs. absoluteelement.href).
- Custom attributes (e.g.,
- Use these methods for:
- Direct Property Access (
element.propertyName):- Use for common, standard HTML attributes (e.g.,
id,src,href,value,checked). - Often more convenient and type-aware.
- For
class, always preferelement.classNameor even better,element.classList(covered in the next lesson). - For
data-*attributes, use thedatasetAPI (element.dataset.attributeName) for cleaner access thangetAttribute.
- Use for common, standard HTML attributes (e.g.,
General Rule: Prefer direct property access when available, as it's often more intuitive and handles some type conversions. Use getAttribute/setAttribute for non-standard or dynamically determined attributes.
Exercise: Attribute Manipulator
Instructions: Given the following (simulated) HTML structure, manipulate its attributes using the learned methods and properties.
<img id="userAvatar" src="default-avatar.png" alt="User Avatar" data-user-id="123">
<a id="profileLink" href="/old-profile">View Profile</a>
<input type="checkbox" id="newsletterSubscribe" checked>
<div id="statusDisplay"></div>
Your Task:
- Select the image element (
userAvatar). - Get its
altattribute value usinggetAttribute()and log it. - Change its
srcattribute to "new-avatar.jpg" using direct property access. - Change its
data-user-idattribute to "456" usingsetAttribute(). - Select the link element (
profileLink). - Change its
hrefto "/new-profile" using direct property access. - Check if
profileLinkhas atargetattribute usinghasAttribute(). If not, add one withsetAttribute()set to_blank. - Select the checkbox (
newsletterSubscribe). - Get its
checkedproperty and log it. Then, set itscheckedproperty tofalse. - Select the
div(statusDisplay). - Add a
data-statusattribute with the value "loading" usingsetAttribute(). - Remove the
data-statusattribute fromstatusDisplayafter 2 seconds (usesetTimeout).

