Once you’ve selected an element, you can change anything about it — its text, HTML, styles, classes, and attributes. This is how vanilla JavaScript makes pages dynamic.
const container = document.querySelector(".user-info");// Read — includes HTML tagsconsole.log(container.innerHTML); // "<strong>Sarah</strong> — Admin"// Write — HTML is parsed and renderedcontainer.innerHTML = "<strong>Sarah Chen</strong> — <em>Editor</em>";
innerHTML parses and renders HTML. Use it when you need to insert structured content.
Never set innerHTML with user input. It creates a cross-site scripting (XSS) vulnerability. If a user types <script>alert('hacked')</script>, it will execute. Use textContent for user-provided data.
// Set to empty string to removecard.style.backgroundColor = "";// Or remove all inline stylescard.removeAttribute("style");
element.style only reads and sets inline styles. It won’t show styles from your CSS files. To read the computed (final) style, use getComputedStyle(element).
// Show/hide an elementconst modal = document.querySelector(".modal");modal.classList.toggle("hidden");// Highlight the active navigation linkconst navLinks = document.querySelectorAll(".nav-link");navLinks.forEach(link => link.classList.remove("active"));clickedLink.classList.add("active");// Dark mode toggledocument.body.classList.toggle("dark-mode");
Prefer classList over element.style for most visual changes. CSS classes are reusable, easier to maintain, and keep your JavaScript focused on logic rather than styling.
const link = document.querySelector("a.docs-link");// Read an attributeconsole.log(link.getAttribute("href")); // "/docs"// Set an attributelink.setAttribute("href", "/new-docs");link.setAttribute("target", "_blank");// Remove an attributelink.removeAttribute("target");// Check if an attribute existslink.hasAttribute("target"); // false
const element = document.querySelector(".notification");// 1. CSS class (preferred)element.classList.toggle("hidden"); // Uses .hidden { display: none }// 2. Style propertyelement.style.display = "none"; // Hideelement.style.display = ""; // Show (revert to CSS default)// 3. Hidden attributeelement.hidden = true; // Hideelement.hidden = false; // Show
The CSS class approach is cleanest. Define a .hidden class in CSS and toggle it with classList.toggle("hidden"). This keeps your styling in CSS and your logic in JavaScript.