Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Styling

DOM Styling lets JavaScript change how elements look on the page without reloading it.


🔹 1. Inline Styling using style property

What happens?

  • JavaScript accesses an element

  • Applies CSS directly on the element

  • This is called inline CSS

Syntax

element.style.propertyName = "value";

📌 CSS properties with hyphens (font-size) become camelCase (fontSize)

Explanation

  1. getElementById("text") selects the <p> element.

  2. style.color changes the text color to blue.

  3. style.fontSize increases the font size.

  4. Styles are applied immediately.


🔹 2. Applying Multiple Styles using cssText

When to use?

  • When you want to apply many styles at once

Explanation

  1. cssText works like writing CSS inside the style attribute.

  2. All styles are applied in one line.

  3. It overwrites previous inline styles.


🔹 3. Styling using CSS Classes (classList.add())

Why this is best?

  • Keeps CSS separate from JavaScript

  • Easier to maintain and reuse

Explanation

  1. CSS class .highlight defines the style.

  2. classList.add() attaches the class to the element.

  3. Browser applies the CSS automatically.


🔹 4. Removing Styles (classList.remove())

Explanation

  1. Removes the class from the element.

  2. CSS styles linked to that class are removed.

  3. Element returns to default style.


🔹 5. Toggle Styles (classList.toggle())

Why toggle?

  • Perfect for dark mode, show/hide, accordion

Explanation

  • If class exists → it removes it

  • If class doesn’t exist → it adds it


🔹 6. Check if a Class Exists (classList.contains())

Explanation

  • Checks whether the element has the class

  • Returns a boolean value


🔹 7. Reading Styles with getComputedStyle()

Why needed?

  • Inline styles may not exist

  • Final styles come from CSS, classes, browser defaults

Explanation

  1. getComputedStyle() reads final applied CSS

  2. Color is returned in RGB format

  3. Works even if style came from a stylesheet


🔹 8. Inline Style vs Class (Best Practice)

Example

// ❌ Inline style (not scalable)
element.style.marginTop = "20px";

// ✅ CSS class (recommended)
element.classList.add("spacing");

Explanation

  • Inline styles are hard to manage

  • Classes allow reuse and cleaner code


✅ Summary Table

Feature

Use

style.property

Quick inline changes

cssText

Multiple inline styles

classList.add()

Apply CSS class

classList.remove()

Remove class

classList.toggle()

Toggle styles

getComputedStyle()

Read final styles


📌 Key Takeaways

✔️ JavaScript uses camelCase for CSS

✔️ Prefer CSS classes over inline styles

✔️ getComputedStyle() shows actual applied CSS