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.
To change the style of an HTML element, use this syntax:
document.getElementById("id").style.property = "new style";
// 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";
background-color) must be written using camelCase (e.g.,
backgroundColor).
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");
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";
}
style property to modify inline stylesclassList is the best way to handle groups of stylesdisplay: none to remove an element from the document
flowvisibility: hidden to hide it while keeping its space