In this article, we'll take a look at how we can modify the attributes, classes, and styles of HTML element nodes.

Modifying Attributes

Attributes are often used in HTML to provide additional information about an element.Ā Some common examples are theĀ srcĀ attribute of anĀ imgĀ tag, theĀ hrefĀ of anĀ aĀ tag, as well asĀ class,Ā idĀ andĀ style. You may also have seen attributes beginning withĀ data-, these areĀ custom attributes that we can also modify.

The methods we have in JavaScript for modifying element attributes are:

hasAttribute()Ā ā€” Returns a Boolean.

getAttribute()Ā ā€” Returns the value of a specific attribute.

setAttribute()Ā ā€” Adds or updates the value of a specific attribute.

removeAttribute()Ā ā€” Removes an attribute from an element.

Letā€™s use the following HTML as our example:

<!DOCTYPE html>
<html lang="en">
<body>

<img src="https://res.cloudinary.com/trobes/image/upload/c_scale,w_400/v1549941322/before.png">

</body>
</html>

Before DOM Example

Open up theĀ consoleĀ and test out the attribute methods:

// Assign image element
const image = document.querySelector('img');

image.hasAttribute('src');       // true
image.getAttribute('src');       // returns the src link
image.removeAttribute('src');    // removes the src

And let's useĀ setAttribute()Ā to assign a new image to ourĀ src:

image.setAttribute('src', 'https://res.cloudinary.com/trobes/image/upload/c_scale,w_400/v1549941322/after.png');

After DOM Example

TheĀ hasAttribute()Ā andĀ getAttribute()Ā methods are often used with conditional statements, whileĀ setAttribute()Ā andĀ removeAttribute()Ā are more often used to directly modify the DOM.

Modifying Classes

When working with CSS, we use classes to apply styles to multiple elements.Ā Letā€™s take a look at how we can work with the class attribute in JavaScript, usingĀ classNameĀ andĀ classList.

classNameĀ ā€” Gets or sets the class value.

classList.add()ā€” Adds class values.

classList.toggle()Ā ā€” Toggles a class on or off.

classList.contains()Ā ā€” Checks if a value exists.

classList.replace()Ā ā€” Replaces old value with a new one.

classList.remove()Ā ā€” Removes a value.

Letā€™s work with each of these methods in the following example:

<!DOCTYPE html>
<html lang="en">
<style>
    .active {
        border: 5px solid green;
    }
    .alert {
        border: 5px solid red;
    }
    .hidden {
        display: none;
    }
    div {
        border: 5px solid lightgrey;
        padding: 15px;
        margin: 5px;
    }
</style>
<body>
    <div>Div #1</div>
    <div class="active">Div #2</div>
</body>
</html>

And hereā€™s the initial HTML output:

Selection DOM Example

We useĀ classNameĀ to assign values to classes:

// Select div #1
const div = document.querySelector('div');

// Assign the alert class to div #1
div.className = 'alert';

Now theĀ alertĀ class defined in our HTML has been assigned to the firstĀ div:

Selection DOM Example 2

This will override any existing classes on the element. You can add multiple classes usingĀ className, if you separate the class names to be applied with spaces.

The other way to modify our classes is with theĀ classListĀ property, and it has a few very useful methods:

// Select div #2 by its class name
const activeDiv = document.querySelector('.active');

// Add the hidden class
activeDiv.classList.add('hidden');   
   
// Remove the hidden class
activeDiv.classList.remove('hidden'); 
  
// Switch between hidden true and false
activeDiv.classList.toggle('hidden');

// Replace active class with alert class
activeDiv.classList.replace('active', 'alert');

After running through these methods, our HTML will render like so:

Selection DOM Example 3

Note:Ā UsingĀ classList.add()Ā will add a new class to the list of existing classes (rememberĀ classNameĀ would override any existing classes). You can also add multiple classes as comma-separated strings.

Modifying Styles

Typically styles are added via separate CSS stylesheets, however, there are times when we might want to use an inline style ā€” and it's useful to know how we can modify it directly with JavaScript! Letā€™s demo this with the following HTML:

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 200px;
                width: 200px;
                border: 5px solid black;
                display: flex;
                justify-content: center;
                align-items: center;">Style me!</div>
</body>
</html>

Our initial output:

Selection DOM Example 4

When working with CSS properties in the DOM, we use camelCase. So instead of using dashes as we would with CSS e.g.border-radius, we use camel case e.g.Ā borderRadius. Where our first word is in lower case and any subsequent words are capitalized.

// Select the div
const div = document.querySelector('div');

// Make div into a circle, change color and font size
div.style.borderRadius = '50%';
div.style.backgroundColor = 'lightgreen';
div.style.fontSize = '30px';

Note:Ā We could useĀ setAttribute()to modify our styles eg.Ā div.setAttribute('style', 'border-radius: 50%');Ā However,Ā this will remove all existing inline styles. So itā€™s much better to use theĀ styleĀ attribute directly.

Our output after adding these styles:

Selection DOM Example 5

Of course, if we have multiple style changes to apply to an element, itā€™s best to apply them to a class in your CSS and just add the new class to the element via JavaScript šŸ†’.

Related Posts:


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰