TExcelTAD
Home › JavaScript › DOM Changing HTML & CSS

DOM Changing HTML & CSS

Once you've selected an element, you can change everything about it: its text, its inner HTML, its attributes, its CSS classes and its inline styles. The browser re-renders the page as soon as your code finishes.

Text and HTML content

Property Reads / writes Notes
textContent plain text safe for any text; tags are shown literally
innerHTML HTML markup parses tags — never use with untrusted input
innerText rendered text like textContent, but respects CSS (hidden text is skipped)
outerHTML the element including its own tag replacing it swaps the element
html · try it yourself
<p id="a">Original text</p>
<p id="b">Original text</p>
<button id="go">Update</button>
<script>
  document.getElementById("go").addEventListener("click", () => {
    const html = "Now with <em>emphasis</em> and <b>bold</b>";
    document.getElementById("a").textContent = html;   // shows the tags as text
    document.getElementById("b").innerHTML = html;     // renders the tags
  });
</script>

Warning: Putting user input into innerHTML allows attackers to inject scripts (XSS). Use textContent, or build elements with createElement, whenever the data isn't your own trusted markup.

Attributes

Most standard HTML attributes are available as properties (img.src, a.href, input.value, el.id). For any attribute, use getAttribute, setAttribute, hasAttribute and removeAttribute. Custom data-* attributes appear in element.dataset:

html · try it yourself
<img id="pic" alt="A grey placeholder" width="120" height="80"
     src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23bbb'/%3E%3C/svg%3E">
<a id="link" href="https://example.com" data-category="docs" data-clicks="0">Example link</a>
<br><button id="swap">Swap image</button> <button id="toggle">Disable button</button>
<script>
  const pic = document.getElementById("pic");
  const link = document.getElementById("link");

  console.log("alt:", pic.getAttribute("alt"));
  console.log("width:", pic.width, typeof pic.width);              // property: a number
  console.log("width attr:", pic.getAttribute("width"));           // attribute: a string
  console.log("category:", link.dataset.category);

  document.getElementById("swap").addEventListener("click", () => {
    pic.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Ccircle cx='60' cy='40' r='35' fill='%23f0db4f'/%3E%3C/svg%3E";
    pic.alt = "A yellow circle";
    link.dataset.clicks = Number(link.dataset.clicks) + 1;
    console.log("clicks:", link.getAttribute("data-clicks"));
  });

  const toggle = document.getElementById("toggle");
  toggle.addEventListener("click", () => {
    const swap = document.getElementById("swap");
    swap.disabled = !swap.disabled;            // boolean attribute via property
    toggle.textContent = swap.disabled ? "Enable button" : "Disable button";
  });
</script>

CSS classes with classList

The cleanest way to change appearance is to toggle CSS classes and keep the actual styles in CSS:

Method Effect
classList.add("a", "b") add classes
classList.remove("a") remove a class
classList.toggle("a") add if missing, remove if present (returns the new state)
classList.toggle("a", force) add if force is true, remove if false
classList.contains("a") check for a class
classList.replace("a", "b") swap one class for another
html · try it yourself
<style>
  .panel { padding: 12px; border-radius: 8px; border: 2px solid #ccc; transition: all .2s; }
  .panel.dark { background: #222; color: #eee; border-color: #555; }
  .panel.big { font-size: 1.4em; }
</style>
<div class="panel" id="panel">I am a panel.</div>
<p>
  <button data-cls="dark">Toggle dark</button>
  <button data-cls="big">Toggle big</button>
</p>
<script>
  const panel = document.getElementById("panel");
  for (const btn of document.querySelectorAll("button[data-cls]")) {
    btn.addEventListener("click", () => {
      const on = panel.classList.toggle(btn.dataset.cls);
      console.log(`${btn.dataset.cls}: ${on ? "on" : "off"} → class="${panel.className}"`);
    });
  }
</script>

Inline styles with style

element.style sets inline styles. CSS property names become camelCase (background-color → backgroundColor), values are strings with units. Setting a style to "" removes it. To read the style actually applied (including from stylesheets), use getComputedStyle:

html · try it yourself
<style> #box { width: 80px; height: 80px; background: steelblue; } </style>
<div id="box"></div>
<p>
  <button id="grow">Grow</button>
  <button id="paint">Next colour</button>
  <button id="reset">Reset</button>
</p>
<script>
  const box = document.getElementById("box");
  const colors = ["tomato", "seagreen", "goldenrod", "steelblue"];
  let size = 80;
  let colorIndex = 0;

  document.getElementById("grow").addEventListener("click", () => {
    size += 20;
    box.style.width = size + "px";
    box.style.borderRadius = size / 4 + "px";
  });
  document.getElementById("paint").addEventListener("click", () => {
    box.style.backgroundColor = colors[colorIndex++ % colors.length];
    console.log("computed background:", getComputedStyle(box).backgroundColor);
  });
  document.getElementById("reset").addEventListener("click", () => {
    size = 80;
    box.removeAttribute("style");   // drop all inline styles
  });
</script>

You can also set CSS custom properties: element.style.setProperty("--accent", "#f0db4f").

Tip: Prefer classList for anything that's a "state" (active, hidden, error, dark). Reserve style for values that are truly dynamic, such as positions or sizes calculated in JavaScript.

Showing and hiding

js
el.hidden = true;                 // the HTML hidden attribute
el.style.display = "none";        // inline style
el.classList.add("is-hidden");    // a class defined in your CSS

Test yourself

Which property should you use to insert text typed by a user?

  1. innerHTML
  2. outerHTML
  3. textContent
  4. insertAdjacentHTML

How do you set the CSS font-size of el to 20px?

  1. el.style.font-size = "20px"
  2. el.style.fontSize = "20px"
  3. el.style.fontSize = 20
  4. el.css("font-size", 20)

What does el.classList.toggle("open") return?

  1. Nothing
  2. The element
  3. true if the class is now present, false otherwise
  4. The list of classes