JS DOM Styles 🎯

beginner
25 min

JS DOM Styles 🎯

Welcome to this comprehensive guide on JavaScript Document Object Model (DOM) Styles! By the end of this tutorial, you'll be styling web pages like a pro. Let's dive in!

Understanding the DOM 📝

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document, allowing you to manipulate its content, HTML, and CSS.

In JavaScript, we can interact with the DOM to dynamically change the appearance and behavior of our web pages.

Accessing Elements 💡

To style elements using JavaScript, we first need to access them. Here's how you can do it:

javascript
// Access the first paragraph in the body let paragraph = document.querySelector('body > p');

In the example above, document.querySelector is a method that finds the first matching element in the document, in this case, the first <p> element within the <body>.

Changing Styles ✅

Once we have access to an element, we can modify its styles using the style property or by creating a <style> tag.

Using the style property

javascript
// Change the color of the first paragraph paragraph.style.color = 'red';

In the example above, we're changing the color of the first paragraph to red using the style property.

Creating a <style> tag

javascript
// Create a new style for the first paragraph let style = document.createElement('style'); style.innerHTML = ` body > p { color: red; } `; document.head.appendChild(style);

In this example, we're creating a new <style> tag, setting its content to change the color of the first paragraph to red, and then adding it to the head of the document.

Advanced Styling 💡

CSS Variables

CSS variables (also known as CSS custom properties) allow you to store and reuse values throughout your styles. Here's an example:

css
:root { --main-color: red; } body > p { color: var(--main-color); }

In this example, we've defined a CSS variable called --main-color and assigned it the value red. We then use this variable to set the color of the first paragraph.

Media Queries

Media queries allow you to apply different styles based on the device's characteristics, like screen size or orientation.

css
@media (min-width: 600px) { body > p { font-size: 20px; } }

In this example, we're applying a font size of 20px to the first paragraph when the viewport's width is 600px or more.

Quiz 💡

Quick Quiz
Question 1 of 1

How can you change the background color of a specific element using JavaScript?

That's it for this lesson! By now, you should have a good understanding of how to style elements using JavaScript.

Remember, practice makes perfect! Keep coding and styling, and you'll be creating beautiful, dynamic web pages in no time. Happy coding! 🎉