Create your own
Lesson illustration

Manipulating Element Attributes

Hello! Welcome back to your front-end development course.

In our last lesson, we learned how to select elements and change their content using textContent and innerHTML. Now that you can find and modify what's inside an element, we'll move on to changing the element's properties and behavior itself.

This lesson focuses on the learning outcome: Dynamically alter element attributes to modify behavior and appearance, such as changing an image's source or toggling a button's disabled state.

We'll explore how to read and change HTML attributes like an image's src, a link's href, or a button's disabled status using JavaScript. This is a fundamental skill for creating interactive experiences, directly translating the concept of component states (like 'active', 'disabled', 'selected') from your design work into functional code.

1. Understanding and Accessing Attributes

HTML attributes are the keywords inside an opening tag that provide additional information about an element. For example, in <img src="photo.jpg" alt="A photo">, src and alt are attributes. JavaScript gives us two main ways to work with them: direct properties and specific methods.

Let's start with a foundational reading that covers the core concepts of getting and setting these attributes.

DOM Manipulation: Attributes ( getAttribute , setAttribute , etc.)

This article, "DOM Manipulation: Attributes", provides a comprehensive overview of how to read, modify, add, and remove attributes. It clearly explains the two primary approaches we'll be using.

Please read the first three main sections: What are HTML Attributes? Accessing Attribute Values (covers getAttribute and direct property access) Modifying Attribute Values (covers setAttribute and direct property assignment) Focus on the difference between using a method like getAttribute('href') and a direct property like element.href. Notice how one gives you the literal value from the HTML, while the other might give you a processed, absolute URL.

To see these methods in action, the following short video provides a practical demonstration.

JavaScript Tutorial For Beginners #35 - Changing Element Attributes

This video from The Net Ninja, "Changing Element Attributes", walks through the process of getting and setting attributes, reinforcing the concepts from the article.

Watch from 00:58 to 03:40. The presenter demonstrates: Using getAttribute() to read the value of href and class. Using setAttribute() to change an existing attribute and add a new one.

2. Key Distinction: Methods vs. Properties

As you've seen, you have two tools for this job:

  1. Methods: getAttribute(name) and setAttribute(name, value).

    • Pro: They work on any attribute, including custom ones (like data-* attributes).
    • Pro: They read/write the literal string value as it appears in the HTML.
    • Con: They can be slightly more verbose.
  2. Direct Properties: element.id, element.src, element.href, etc.

    • Pro: More concise and often easier to read (image.src = 'new.jpg').
    • Pro: They are "live" and can handle different data types (e.g., button.disabled is a true/false boolean).
    • Con: They only exist for standard, well-known attributes. You can't use element.data-user-id.

General Rule: For common attributes like id, src, href, and value, using direct properties is usually preferred. For custom attributes or when you need the exact HTML value, use getAttribute() and setAttribute().

3. Practical Use Case: Changing an Image's Source

One of the most common uses for attribute manipulation is to change an image dynamically. This could be for an image gallery, a product customizer, or showing a different icon based on a state.

The core of this is simple: select the <img> element and set its src property to a new URL.

const profilePic = document.querySelector('#profile-picture');

// Change the image
profilePic.src = 'images/new-avatar.png'; 

The video below, while building a full image slider, contains the essential logic for this.

Javascript Image Slider With Next Aand Prev Buttons | JavaScript Project For Students | #SmartCode

This video demonstrates building an image slider. We're interested in the specific moment where the image's src attribute is updated to show the next picture.

Watch the segment from 08:55 to 09:30. Notice how the code gets the image element and then assigns a new value to image.src to display a different picture from an array.

4. Practical Use Case: Disabling a Button

In UI/UX design, you often define states for interactive elements. A "Submit" button, for instance, should be disabled until a form is valid. This prevents errors and guides the user. In HTML, this is controlled by the disabled attribute.

You can dynamically control this state in JavaScript.

How to disable a button in JavaScript

This article, "How to disable a button in JavaScript", focuses on this exact task. It's a perfect example of changing an element's behavior based on application logic.

Read the sections "Selecting and Disabling Buttons in JavaScript", "Conditional Disabling Based on User Input", and "Toggling Button States with Attributes". Pay attention to the recommended approach of setting the disabled property to true or false.

As the article explains, the cleanest way to control this is with the boolean disabled property:

const submitButton = document.querySelector('#submit-button');

// To disable the button
submitButton.disabled = true;

// To enable the button
submitButton.disabled = false;

This is more direct than using setAttribute and removeAttribute for this specific boolean attribute.

5. Your Turn: The Light Switch

Let's apply these concepts to build a simple interactive component: a light switch.

Here is the starting HTML. You will need two images: one for the "off" state and one for the "on" state. You can use these URLs for placeholder images:

  • Off: https://placehold.co/100x180/000000/FFFFFF?text=OFF
  • On: https://placehold.co/100x180/FFFF00/000000?text=ON
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Light Switch</title>
    <style>
        body { text-align: center; font-family: sans-serif; }
        #lightbulb { border: 1px solid #ccc; margin-top: 20px; }
        button { margin: 10px; padding: 10px 20px; font-size: 16px; }
    </style>
</head>
<body>

    <h1>The Light Switch</h1>
    <img id="lightbulb" src="https://placehold.co/100x180/000000/FFFFFF?text=OFF" alt="A lightbulb that is off">
    
    <div>
        <button id="toggle-button">Toggle Light</button>
        <button id="disable-button">Disable Switch</button>
    </div>

    <script>
        // Your JavaScript code will go here.
        // We will use .onclick for now to attach behavior to the buttons.
        // We'll learn a better way with addEventListener in a future lesson.

        const lightbulb = document.querySelector('#lightbulb');
        const toggleButton = document.querySelector('#toggle-button');
        const disableButton = document.querySelector('#disable-button');

        const imgOff = 'https://placehold.co/100x180/000000/FFFFFF?text=OFF';
        const imgOn = 'https://placehold.co/100x180/FFFF00/000000?text=ON';

        // Task 1: Add logic to the toggle button
        toggleButton.onclick = function() {
            // Your code here to check the current src and change it.
            // Also, change the 'alt' text to be accurate!
        };

        // Task 2: Add logic to the disable button
        disableButton.onclick = function() {
            // Your code here to disable the toggle button.
            // Bonus: Also change this button's text to "Switch Disabled".
        };
    </script>

</body>
</html>

Your Task:

  1. Copy the code into an HTML file.
  2. Inside toggleButton.onclick: Write an if/else statement.
    • Check if the lightbulb.src is currently the "off" image (imgOff).
    • If it is, change the src to the "on" image (imgOn) and update the alt attribute to "A lightbulb that is on".
    • Otherwise, change the src back to the "off" image and update the alt attribute accordingly.
  3. Inside disableButton.onclick: Write the code to set the disabled property of the toggleButton to true.
Click here to see the solution
// Task 1: Add logic to the toggle button
toggleButton.onclick = function() {
    if (lightbulb.src === imgOff) {
        // Turn the light on
        lightbulb.src = imgOn;
        lightbulb.alt = 'A lightbulb that is on';
    } else {
        // Turn the light off
        lightbulb.src = imgOff;
        lightbulb.alt = 'A lightbulb that is off';
    }
};

// Task 2: Add logic to the disable button
disableButton.onclick = function() {
    // Disable the toggle button
    toggleButton.disabled = true;
    
    // Bonus: Update the button text
    disableButton.textContent = 'Switch Disabled';
};

Conclusion

Excellent work! You've now mastered a critical part of DOM manipulation. By changing attributes, you can alter not just what an element looks like, but how it behaves.

Key Takeaways:

  • Attributes like src, href, and disabled control the appearance and behavior of HTML elements.
  • You can read and write attributes using either direct properties (element.src) or methods (element.setAttribute()).
  • Direct properties are often more convenient for standard attributes and can handle non-string types like booleans (.disabled).
  • setAttribute() is essential for custom attributes and when you need the exact string value from the HTML.
  • This skill allows you to build interactive components like image galleries, lightboxes, and dynamic forms.

In our next lesson, we'll focus on one specific attribute: class. You'll learn how to add, remove, and toggle CSS classes on elements using classList, which is the modern and preferred way to dynamically change an element's styling.

Can't find a good explanation? Sign up and we'll make it for you

Sign up