Setting and Getting CSS Styles in JavaScript
In this article, we’re going to take a look at how we can set and get CSS styling with JavaScript.
Setting CSS Properties with JavaScript
Let’s start off with an HTML paragraph tag:
<p id="inline" style="color: green">I'm green text.</p>
Notice we’re styling the paragraph tag to be of color green. Generally, it’s recommended to avoid inline-styling like this, as it can become quite messy. Nonetheless, let’s take a look at how we can use JavaScript to change the color of the text, and perform some other interesting operations on the paragraph tag.
First, let’s store the element in a variable called paragraph
.
const paragraph = document.getElementById("inline");
To recap: we have selected the paragraph tag, storing it in a JavaScript variable, paragraph
. In order to change the color, we’ll need to attach some methods onto the variable, like so:
...
paragraph.style.color = 'blue';
The color of the paragraph should now be blue.
However, there’s a problem – the paragraph says “I’m green text”, but now it’s blue. Can we fix this? Of course! Let’s declare a new variable, color
, and use a template literal to display the appropriate color.
const paragraph = document.getElementById("inline");
const color = "blue";
paragraph.style.color = color;
paragraph.innerHTML = `I'm ${color} text.`;
Perfect! A little taste of the power of programming. Try swapping the color
variable to a color of your choice. As long as the color is known (for example, red, yellow, pink. You can find a list of available colors on W3C), the behavior will be as expected. However, if you were to use a random string of characters within the color
variable, i.e. const color = 'kjdslf';
, the paragraph will revert to the green color which was obtained from the inline-style.
Note: You can also use hex color codes, such as #333
, but the paragraph will look a bit strange!
More CSS Styling
As you might have guessed, you can indeed attach any CSS you’d like to HTML elements. Let’s explore a few examples.
const paragraph = document.getElementById("inline");
const color = "blue";
paragraph.style.color = color;
paragraph.style.fontWeight = 900;
paragraph.style.fontSize = "2em";
paragraph.style.textAlign = "center";
Notice that we’re using camelCase rather than adding a dash ("-") between the styling properties (e.g. fontWeight rather than font-weight). This is required if we’re going to set CSS with JavaScript.
So far, we’ve only been setting a single CSS property at a time, but there are two ways which allow us to set multiple properties.
Setting multiple styles with cssText
CssText is simply a way to set multiple styles to an element.
Let’s take our example above, and combine some of the code:
const paragraph = document.getElementById("inline");
paragraph.style.cssText = "color: blue; font-size: 2em; text-align: center";
And that’s it! We’ve set multiple CSS properties using cssText
. Notice we’ve included a dash this time, as it’s necessary.
Setting multiple styles with setAttribute()
Another way to set multiple CSS properties with JavaScript is with the setAttribute()
function. setAttribute()
takes two arguments:
name
- A string specifying the name of the attribute whose value is to be set.value
- A string containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.
const paragraph = document.getElementById("inline");
paragraph.setAttribute(
"style",
"color: blue; font-size: 2em; text-align: center"
);
In the example above, style
is the string specifying the name of the attribute, and the string after (the styling) is the value
.
If, for any reason, you’d like to unset the attributes, you can make use of removeAttribute()
, like so:
const paragraph = document.getElementById("inline");
// Adding attribute
paragraph.setAttribute(
"style",
"color: blue; font-size: 2em; text-align: center"
);
// Removing the attribute
paragraph.removeAttribute("style");
removeAttribute()
is only passed one argument, the attribute with the specified name from the element.
Note: When you set CSS with cssText
or setAttribute()
, any inline-CSS you’ve already had will be overwritten.
Getting CSS styles on an element
It’s quite easy to look at CSS styling attached to an element. Let’s explore two different ways. You are probably familiar with the first, console.log()
.
const paragraph = document.getElementById("inline");
paragraph.setAttribute(
"style",
"color: blue; font-size: 2em; text-align: center"
);
// Showing all of the styling on the element
console.log(paragraph.style);
// Targeting specific properties
console.log(paragraph.style.color);
The console results:
If we click that first console result, we’ll get a very long list of possible properties we can set with JavaScript:
Note: console.log(element.style)
will only display inline-styles. It will not show you styling from an external file (e.g. styles.css
).
If we want to display all of the styling within a page, we can use getComputedStyle()
.
From MDN:
“The window.getComputedStyle()
method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.”
Let’s take a look.
const paragraph = document.getElementById("inline");
console.log(getComputedStyle(paragraph));
The results:
Notice we no longer have empty strings. Instead, we’re seeing all of the styling set by various sources, including the browser.
Conclusion
In this article, we’ve looked at a few ways to set CSS with JavaScript. Although it isn’t really common for modern developers to write JavaScript like this, it’s still useful to know how to do it. The modern-day frameworks and libraries compile to vanilla JavaScript, afterall.
Related Posts
The Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating a Real Time Chat Application with React, Node, and TailwindCSS
In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.
Read more