HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM CSS

The HTML DOM allows JavaScript to change the style of HTML elements dynamically. This means you can change visibility, colors, fonts, and layouts in response to user actions.


The style Property

To change the style of an HTML element, use this syntax:

document.getElementById("id").style.property = "new style";

Examples:

// Change color to blue
document.getElementById("p2").style.color = "blue";

// Change background color
document.getElementById("main").style.backgroundColor = "yellow";

// Hide an element
document.getElementById("intro").style.display = "none";
Naming Convention: In JavaScript, CSS properties that contain a hyphen (e.g., background-color) must be written using camelCase (e.g., backgroundColor).

DOM TokenList (classList)

Instead of changing individual styles, it is often better to add or remove predefined CSS classes from your stylesheet. This keeps your JavaScript clean and your styles modular.

const element = document.getElementById("myDIV");

// Add a class
element.classList.add("mystyle");

// Remove a class
element.classList.remove("mystyle");

// Toggle a class (Add if missing, Remove if present)
element.classList.toggle("dark-mode");

Visibility Control

JavaScript can be used to show or hide elements, which is the basis for accordions, modals, and dropdown menus.

function hideElement() {
  document.getElementById("p1").style.visibility = "hidden";
}

function showElement() {
  document.getElementById("p1").style.visibility = "visible";
}

Key Points to Remember

  • Use the style property to modify inline styles
  • hyphenated-properties become camelCaseProperties
  • Values must be strings (e.g., "100px", "red")
  • classList is the best way to handle groups of styles
  • Use display: none to remove an element from the document flow
  • Use visibility: hidden to hide it while keeping its space
  • Style changes can be triggered by events (clicks, hovers, etc.)