JavaScript for Beginners: Mastering DOM Manipulation Step-by-Step

2.51K 0 0 0 0

📘 Chapter 4: Styling and Class Manipulation

🎨 Introduction: Make It Look Good with JavaScript

Changing text and content is great—but what really brings your webpage to life is styling. Whether you want to highlight important content, hide/show elements, or apply visual effects on the fly, JavaScript allows you to manipulate CSS dynamically using:

  • Direct styling via .style
  • CSS class management using .classList
  • Adding, removing, toggling, and checking classes
  • Building interactive UI features like dark mode, tabs, dropdowns, and animations

Let’s dive in and turn your static designs into interactive, styled experiences.


🛠️ 1. Styling Elements Directly with .style

The simplest way to apply styles is through the style property on any DOM element.

🔹 Syntax:

javascript

 

element.style.propertyName = "value";

Note: Property names use camelCase (e.g., backgroundColor, not background-color).


🧾 Example:

html

 

<p id="text">Hello World!</p>

javascript

 

const text = document.getElementById('text');

text.style.color = "red";

text.style.fontSize = "20px";

text.style.fontWeight = "bold";


🔍 Commonly Used Style Properties:

JavaScript

CSS Equivalent

Use Case

backgroundColor

background-color

Change background color

color

color

Text color

fontSize

font-size

Text size

margin, padding

margin, padding

Spacing

display

display

Show/hide elements

visibility

visibility

Hide without layout shift

width, height

width, height

Sizing elements


️ Limitation:

  • Styling with .style only affects inline styles, not external or embedded CSS.
  • Not great for complex styles or reusable patterns — that’s where class manipulation comes in.

🎯 2. Working with CSS Classes Using .classList

Instead of setting each style individually, you can define styles in your CSS and toggle them with JavaScript using classList.

🔹 HTML:

html

 

<div id="card" class="box">Content</div>

🔹 CSS:

css

 

.highlight {

  border: 2px solid orange;

  background-color: #fffbe6;

}

🔹 JavaScript:

javascript

 

const card = document.getElementById('card');

card.classList.add('highlight');


📚 .classList Methods Explained

Method

Description

Example

.add()

Adds a class if it’s not already there

element.classList.add("active")

.remove()

Removes a class

element.classList.remove("hidden")

.toggle()

Adds class if not present, removes if it is

element.classList.toggle("dark")

.contains()

Checks if class exists

element.classList.contains("open")


🧪 Example: Toggle Dark Mode

html

 

<button id="themeBtn">Toggle Theme</button>

<body id="body"></body>

css

 

.dark-mode {

  background-color: #121212;

  color: white;

}

javascript

 

const btn = document.getElementById('themeBtn');

const body = document.getElementById('body');

 

btn.addEventListener('click', () => {

  body.classList.toggle('dark-mode');

});


📦 3. Combining Classes and Inline Styles

You can use both .style and .classList together for flexible styling:

javascript

 

element.classList.add('error');

element.style.border = "1px solid red";

Use:

  • .classList for consistent, reusable styles
  • .style for temporary or inline changes

🧠 4. Conditional Styling Based on Events

You can dynamically apply or remove classes/styles based on user interaction:

🔹 Example: Highlight Active Tab

html

 

<ul>

  <li class="tab">Tab 1</li>

  <li class="tab">Tab 2</li>

</ul>

javascript

 

const tabs = document.querySelectorAll('.tab');

 

tabs.forEach(tab => {

  tab.addEventListener('click', () => {

    tabs.forEach(t => t.classList.remove('active'));

    tab.classList.add('active');

  });

});


👁️ 5. Hide/Show Elements Dynamically

🔹 Using display:

javascript

 

element.style.display = "none"; // hide

element.style.display = "block"; // show

️ Removes the element from layout flow


🔹 Using visibility:

javascript

 

element.style.visibility = "hidden"; // hides but retains space

element.style.visibility = "visible";


🔹 Using Classes:

css

 

.hidden {

  display: none;

}

javascript

 

element.classList.add('hidden');

element.classList.remove('hidden');


🎨 6. Adding Styles to Multiple Elements

You can loop through elements and apply styles or classes:

javascript

 

const cards = document.querySelectorAll('.card');

 

cards.forEach(card => {

  card.classList.add('highlight');

});


📐 Advanced Example: Interactive Card Hover

🔹 HTML:

html

 

<div class="card">Hover over me</div>

🔹 CSS:

css

 

.card {

  padding: 20px;

  border: 1px solid #ccc;

  transition: all 0.3s ease;

}

 

.card.hovered {

  transform: scale(1.05);

  box-shadow: 0 4px 10px rgba(0,0,0,0.1);

}

🔹 JavaScript:

javascript

 

const card = document.querySelector('.card');

 

card.addEventListener('mouseenter', () => card.classList.add('hovered'));

card.addEventListener('mouseleave', () => card.classList.remove('hovered'));


📊 Summary Table

Task

Method

Example

Change color

.style.color

el.style.color = "red";

Add class

.classList.add()

el.classList.add("active")

Remove class

.classList.remove()

el.classList.remove("hidden")

Toggle theme

.classList.toggle()

el.classList.toggle("dark-mode")

Inline CSS

.style.property

el.style.marginTop = "10px";


🧱 Best Practices

  • Use CSS classes for maintainability
  • Avoid overusing .style for complex UIs
  • Keep styles in your CSS file — let JS handle logic
  • Use transitions in CSS for smoother effects
  • Test changes across different screen sizes and browsers

💡 Real-World Styling Use Cases

Feature

DOM Use

Dark mode toggle

.classList.toggle("dark")

Toast/alert display

el.style.display = "block"

Input validation

Add/remove error class

Dropdowns & menus

Use hidden class or toggle visibility

Active tabs

Loop and highlight selected tab


📍 Summary: What You’ve Learned

  • How to change styles directly using .style.property
  • How to manage reusable styles with .classList methods
  • The difference between inline styles and CSS classes
  • Real-life interactive UI components powered by DOM + CSS
  • Tips for writing maintainable, scalable JavaScript styles


Next up: Creating, Cloning, and Removing DOM Elements — where we’ll dynamically build content from scratch.

Back

FAQs


1. What is the DOM in JavaScript?

A: The DOM (Document Object Model) is a tree-like structure that represents your web page. JavaScript can access and modify this structure to change elements, styles, content, and more—dynamically and in real-time.

2. Is the DOM part of JavaScript?

A: Not exactly. The DOM is a Web API provided by the browser, but JavaScript interacts with it using built-in methods like getElementById, querySelector, and addEventListener.

3. How do I select an element using JavaScript?

Use DOM methods like:

document.getElementById('id')

document.querySelector('.class')

document.querySelector('tag')

4. What’s the difference between innerHTML and textContent?

  • textContent only sets or gets plain text.
  • innerHTML lets you read or change the HTML structure, including tags.

5. How do I change the style of an element using JavaScript?

element.style.color = "red";

element.style.backgroundColor = "yellow";

Or better, toggle CSS classes:

element.classList.add('active');

element.classList.remove('hidden');

6. How do I add a new element to the page dynamically?

const div = document.createElement('div');

div.textContent = "Hello!";

document.body.appendChild(div);

7. How do I remove elements from the DOM?

element.remove(); // Modern way

// OR

element.parentNode.removeChild(element); // Older method

8. How do I handle user clicks or input with JavaScript?

const button = document.querySelector('button');

button.addEventListener('click', function() {

  alert('Button clicked!');

});

9. What are some beginner DOM projects I can try?

  • To-do list
  • Click counter
  • Image gallery with buttons
  • Live character counter for input fields
  • Simple calculator
  • Dark/light mode toggle