Table of Contents
JavaScript is a powerful language, allowing you to do so many things programmatically.
One of the common uses of JavaScript is to change the color of an element after it is loaded.
In this post, we will learn how you can use JavaScript to change the color of an HTML element.
Change the color of an element
To start off, let's use this example DOM:
HTML<body>
<p class="content">
Hello World!
</p>
</body>
The text we want to change is the paragraph element that says "Hello World!".
To start, we will need to first query for the element.
We can use JavaScript's document.querySelector()
function to do this, and pass in the CSS selector for the element we want to change.
JAVASCRIPTconst element = document.querySelector(".content");
Now that we got the element, we can proceed to change the color of the text.
To change the color of the text, we'll be setting its style.color
property. This is a built-in property for HTML elements that represents the color of the text.
All we need to do is change this property to the color that we want, and the browser will take care of the rest.
Here's how to change the color to red
:
JAVASCRIPTconst element = document.querySelector(".content");
element.style.color = "red";
It also supports hexadecimal colors, like #ff0000
.
Conclusion
In this post, we learned how to change the color of an HTML element using JavaScript.
By manipulating the style.color
property, we can both read and update the color of the element.
Hopefully, this has been useful for you. Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Deno
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React