Adding and Removing Attributes

Introduction

In this guide, you will learn how to add, remove, and retrieve attributes from DOM elements using JavaScript. These techniques are essential for dynamically controlling the appearance and behavior of elements on a webpage.

Key Methods:

Element.getAttribute()

This method is used to get the current value of a specific attribute on a DOM element.

Example:


HTML:
<div class="normal-div" id="first-div">
     contents of div 
</div>

JavaScript:
const firstDiv = document.getElementById("first-div");
console.log(firstDiv.getAttribute("class")); // Output: "normal-div"
            

Element.setAttribute()

Use this method to set or update the value of an attribute on a DOM element. It takes two arguments: the name of the attribute and the value to assign.

Example:


HTML:
<p id="example-paragraph">
    contents of paragraph
</p>

JavaScript:
const paragraph = document.getElementById("example-paragraph");
paragraph.setAttribute("class", "summary");
console.log(paragraph.getAttribute("class")); // Output: "summary"
            

Element.removeAttribute()

Use this method to remove an attribute from a DOM element. It takes one argument: the name of the attribute to remove.

Example:


HTML:
<button id="test-button" class="primary">Click me!</button>

JavaScript:
const button = document.getElementById("test-button");
button.removeAttribute("class");
            

Common Use Cases

These methods are particularly useful for dynamically modifying the appearance and behavior of elements on a webpage. Below are some common scenarios:

1. Controlling Element Visibility

You can use attributes like hidden to control the visibility of elements:


const adminButton = document.getElementById("admin-button");
adminButton.setAttribute("hidden", true); // Hides the button
adminButton.removeAttribute("hidden"); // Makes the button visible again
            

2. Disabling Elements

Use the disabled attribute to prevent user interaction:


const submitButton = document.getElementById("submit-button");
submitButton.setAttribute("disabled", true); // Disables the button
submitButton.removeAttribute("disabled"); // Re-enables the button
            

3. Dynamically Updating Elements

Update attributes based on user actions or data:


const image = document.getElementById("profile-pic");
image.setAttribute("src", "new-image-url.jpg"); // Changes the image source
            

What You Learned

In this guide, you explored how to:

These techniques are invaluable for creating dynamic and interactive web applications.