JavaScript DOM Changing HTML

Once you have an element, you can rewrite its text, its markup, and its attributes to update what the user sees.

Changing the content of an element

The two most common ways to change what is inside an element are textContent and innerHTML. Use textContent when you only need to set plain text, and innerHTML when you want the string to be parsed as HTML and turned into real elements. textContent is both simpler and safer, so reach for it first.

textContent versus innerHTML

<!DOCTYPE html>
<html>
<body>

<div id="box"></div>

<script>
const box = document.getElementById("box");

// Plain text: the tags are shown literally, not parsed
box.textContent = "Hello <b>world</b>";

// HTML: the <b> tag becomes real bold formatting
box.innerHTML = "Hello <b>world</b>";
</script>

</body>
</html>
Note: Never pass text that came from a user straight into innerHTML. If that text contains markup or a script tag, the browser will run it, which opens the door to cross-site scripting attacks. Use textContent for untrusted input.

Changing attributes

Attributes such as src, href, alt, and id can be changed in two ways. Many common attributes are available directly as properties, and any attribute can be read or set with getAttribute and setAttribute. Changing an attribute updates the element instantly.

Updating attributes

<!DOCTYPE html>
<html>
<body>

<img id="logo" src="/images/logo.png" alt="Company logo">

<script>
const logo = document.querySelector("#logo");

// Property style for common attributes
logo.src = "/images/new-logo.png";
logo.alt = "Updated company logo";

// Method style works for any attribute
logo.setAttribute("width", "120");
console.log(logo.getAttribute("width")); // "120"
</script>

</body>
</html>

Adding and removing elements

To change the structure of the page, create elements with createElement, insert them with append or prepend, and take them out with remove. Building the element in memory first and attaching it once keeps the page from reflowing more than necessary.

Inserting and deleting elements

<!DOCTYPE html>
<html>
<body>

<ul id="messages">
  <li>Welcome!</li>
</ul>

<script>
const list = document.getElementById("messages");

// Create and add a new item
const item = document.createElement("li");
item.textContent = "A new message";
list.append(item);

// Remove the first item, if there is one
const first = list.firstElementChild;
if (first) {
  first.remove();
}
</script>

</body>
</html>

Content methods at a glance

MemberEffectWhen to use
textContentSets or reads plain textSafe text updates
innerHTMLSets or reads parsed HTMLTrusted markup only
setAttribute()Adds or updates an attributeAny attribute
append() / prepend()Adds child contentInsert new elements
remove()Detaches the elementDelete an element
Note: Reading innerHTML gives you the current markup as a string, which is a quick way to inspect what an element contains while you are debugging.