JavaScript Changing HTML Elements

JavaScript allows you to change HTML elements dynamically after a webpage has loaded. You can update text, insert HTML, modify attributes, change CSS styles, and add or remove classes without reloading the page.

These operations are part of DOM manipulation. The Document Object Model (DOM) represents an HTML document as a collection of objects that JavaScript can access and modify.

In this tutorial, you will learn how to use textContent, innerHTML, innerText, attributes, styles, and classes to change HTML elements.

Changing HTML Content with textContent

The textContent property gets or sets the text content of an HTML element and its descendants.

When you assign a value to textContent, the browser replaces the element’s existing child content with a text node. Any HTML tags included in the assigned string are treated as ordinary text rather than HTML markup.

Syntax of textContent

element.textContent;

To change the text:

element.textContent = "New text";

Example of textContent

HTML:

<p id="message">Hello, World!</p>

JavaScript:

const message = document.querySelector("#message");

message.textContent = "Welcome to JavaScript!";

Updated HTML:

<p id="message">Welcome to JavaScript!</p>

The paragraph’s original text is replaced with the new text.

Getting Text with textContent

You can also use textContent to read the text inside an element.

<h2 id="heading">JavaScript Tutorial</h2>
const heading = document.querySelector("#heading");

console.log(heading.textContent);

Output:

JavaScript Tutorial

textContent Treats HTML as Text

Consider this example:

<p id="demo">Original content</p>
const demo = document.querySelector("#demo");

demo.textContent = "<strong>Hello</strong>";

The browser displays the literal text:

<strong>Hello</strong>

It does not make the text bold because textContent does not parse the assigned string as HTML.

When to use textContent: Use it when you want to read or replace text without interpreting the input as HTML. It is generally a good choice for inserting text from users or other untrusted sources.

Changing HTML Content with innerHTML

The innerHTML property gets or sets the HTML markup inside an element.

Unlike textContent, innerHTML parses an assigned string as HTML. This allows you to create elements, insert tags, and change the structure of an element’s contents.

Syntax of innerHTML

element.innerHTML;

To change the HTML:

element.innerHTML = "<strong>New content</strong>";

Example of innerHTML

HTML:

<div id="content">
  <p>Original paragraph</p>
</div>

JavaScript:

const content = document.querySelector("#content");

content.innerHTML = "<h2>Welcome</h2><p>Learn JavaScript</p>";

Updated HTML:

<div id="content">
  <h2>Welcome</h2>
  <p>Learn JavaScript</p>
</div>

The browser parses the string and creates the heading and paragraph elements inside the div.

Adding HTML Elements Dynamically

You can use innerHTML to insert a list of items.

<ul id="languages"></ul>
const languages = document.querySelector("#languages");

languages.innerHTML = `
  <li>JavaScript</li>
  <li>Python</li>
  <li>Java</li>
`;

Result:

The webpage displays a list containing JavaScript, Python, and Java.

Important Security Warning About innerHTML

Avoid inserting untrusted user input directly into innerHTML. If the input contains malicious HTML or event-handler attributes, it may create a cross-site scripting (XSS) vulnerability.

For example, when displaying a user’s comment as plain text, prefer:

const comment = document.querySelector("#comment");

comment.textContent = userInput;

Here, userInput represents a string obtained from a user or another external source. Using textContent prevents that string from being interpreted as HTML.

Use innerHTML when you genuinely need to insert HTML markup and can ensure that the content is trusted or properly sanitized.

Difference Between textContent and innerHTML

Both properties can replace an element’s content, but they handle the assigned string differently.

FeaturetextContentinnerHTML
Reads contentReturns text contentReturns HTML markup
Sets contentCreates text contentParses HTML markup
Recognizes HTML tags in assigned stringsNoYes
Security for plain untrusted textGenerally saferRequires care
Typical useUpdating messages and labelsCreating or replacing HTML structure

Example:

<div id="demo"></div>
const demo = document.querySelector("#demo");

demo.textContent = "<b>Hello</b>";

The browser displays <b>Hello</b> as plain text.

If you instead write:

demo.innerHTML = "<b>Hello</b>";

The browser displays Hello in bold.

Changing Visible Text with innerText

The innerText property gets or sets the rendered text of an element. It is designed to reflect the text a user would typically see on the page.

Unlike textContent, innerText takes CSS styling and rendered visibility into account when reading text.

Example of innerText

HTML:

<p id="message">Hello, World!</p>

JavaScript:

const message = document.querySelector("#message");

message.innerText = "Text updated successfully!";

The paragraph displays:

Text updated successfully!

For simple text updates, innerText and textContent often produce the same visible result.

Difference Between innerText and textContent

Consider this HTML:

<div id="example">
  Hello
  <span style="display: none;">Hidden text</span>
  World
</div>

JavaScript:

const example = document.querySelector("#example");

console.log(example.textContent);
console.log(example.innerText);

The results differ because textContent includes text inside the hidden span, while innerText normally excludes text that is not rendered.

The output is conceptually:

Hello
  Hidden text
World

Hello World

Exact whitespace and line breaks can vary with the document structure and browser rendering.

textContent vs innerText vs innerHTML

FeaturetextContentinnerTextinnerHTML
Main purposeRead or set text contentRead or set rendered textRead or set HTML markup
Includes hidden descendant text when readingYesUsually noReturns markup, including hidden elements
Parses assigned HTMLNoNoYes
Considers CSS rendering when readingNoYesNo, it returns markup
Best usePlain text manipulationRendered text manipulationTrusted HTML manipulation

For most simple text updates, textContent is a good default because it does not require the browser to calculate rendered text.

Changing HTML Attributes with JavaScript

HTML attributes provide information about an element. Examples include id, class, src, href, alt, and title.

JavaScript provides methods such as getAttribute(), setAttribute(), removeAttribute(), and hasAttribute() for working with attributes.

Using getAttribute()

The getAttribute() method reads the value of an attribute.

HTML:

<img id="photo" src="photo.jpg" alt="Profile photo">

JavaScript:

const photo = document.querySelector("#photo");

console.log(photo.getAttribute("alt"));

Output:

Profile photo

Using setAttribute()

The setAttribute() method creates an attribute or updates its existing value.

HTML:

<img id="photo" src="old-photo.jpg" alt="Old image">

JavaScript:

const photo = document.querySelector("#photo");

photo.setAttribute("src", "new-photo.jpg");
photo.setAttribute("alt", "New profile photo");

The image’s src and alt attributes are updated.

Using removeAttribute()

The removeAttribute() method removes an attribute from an element.

<input id="username" type="text" disabled>
const username = document.querySelector("#username");

username.removeAttribute("disabled");

The disabled attribute is removed, allowing the input to be enabled unless another condition prevents interaction.

Using hasAttribute()

The hasAttribute() method checks whether an element has a particular attribute.

<button id="submit" disabled>Submit</button>
const button = document.querySelector("#submit");

console.log(button.hasAttribute("disabled"));

Output:

true

Because the button contains the disabled attribute, the method returns true.

Updating Common Attributes

<a id="link" href="https://example.com">Visit website</a>
const link = document.querySelector("#link");

link.setAttribute("href", "https://web4learners.com");
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener");

This changes the link destination and configures it to open in a new browsing context. The rel="noopener" attribute helps prevent the opened page from accessing the original page through window.opener.

For attributes that correspond to DOM properties, such as an input’s current value, the property and attribute may not always represent the same state. Use the appropriate property when you need the element’s current live value.

Changing CSS Styles with JavaScript

JavaScript can modify an element’s inline CSS styles through its style property.

The style property allows you to set individual CSS declarations directly on an element.

Changing a Single CSS Property

HTML:

<p id="message">Hello, JavaScript!</p>

JavaScript:

const message = document.querySelector("#message");

message.style.color = "blue";

The paragraph’s text becomes blue.

Changing Multiple CSS Properties

const message = document.querySelector("#message");

message.style.color = "blue";
message.style.backgroundColor = "lightyellow";
message.style.fontSize = "24px";
message.style.padding = "10px";

This updates the text color, background color, font size, and padding.

Notice that CSS property names written in JavaScript use camelCase. For example, background-color becomes backgroundColor, and font-size becomes fontSize.

Using setProperty()

You can also set a CSS property using its standard CSS name with style.setProperty().

const message = document.querySelector("#message");

message.style.setProperty("background-color", "lightblue");
message.style.setProperty("font-size", "20px");

This approach is useful when you want to work with CSS property names as strings.

Removing an Inline Style

Use removeProperty() to remove a specific inline CSS declaration.

const message = document.querySelector("#message");

message.style.removeProperty("color");

This removes the inline color declaration. The element’s final color then depends on any remaining stylesheet rules and inherited styles.

Important: The style property changes inline styles. For larger design changes, using CSS classes is usually more maintainable than setting many individual style properties in JavaScript.

Changing HTML Classes with JavaScript

CSS classes let you apply groups of styles to HTML elements. JavaScript can add, remove, toggle, or check classes using the classList property.

The classList property provides a convenient way to change classes without replacing the element’s entire class attribute.

Using classList.add()

The add() method adds one or more classes to an element.

HTML:

<p id="message">Welcome to JavaScript</p>

CSS:

.highlight {
  color: blue;
  font-weight: bold;
}

JavaScript:

const message = document.querySelector("#message");

message.classList.add("highlight");

The paragraph now uses the highlight class, so the text becomes blue and bold.

Using classList.remove()

The remove() method removes one or more classes from an element.

message.classList.remove("highlight");

The highlight class is removed. Any styles that depended on that class no longer apply unless another rule provides them.

Using classList.toggle()

The toggle() method adds a class if it is absent and removes it if it is present.

message.classList.toggle("highlight");

Calling this statement again reverses the previous change.

You can also force a particular state:

message.classList.toggle("highlight", true);

This ensures the class is present.

message.classList.toggle("highlight", false);

This ensures the class is absent.

Using classList.contains()

The contains() method checks whether an element has a specific class.

console.log(message.classList.contains("highlight"));

Output if the class is present:

true

If the element does not have that class, the result is false.

Practical Example: Toggle Dark Mode

HTML:

<button id="themeButton">Toggle Dark Mode</button>

<div id="page">
  <h2>Welcome</h2>
  <p>This is a theme example.</p>
</div>

CSS:

.dark-mode {
  background-color: #222;
  color: white;
}

JavaScript:

const themeButton = document.querySelector("#themeButton");
const page = document.querySelector("#page");

themeButton.addEventListener("click", function () {
  page.classList.toggle("dark-mode");
});

Whenever the user clicks the button, the dark-mode class is toggled on the page container. The CSS class controls the appearance.

This approach separates the visual design from the JavaScript logic, making the code easier to maintain.

Complete Example of Changing HTML Elements

The following example combines text, attributes, styles, and classes in one simple interactive webpage.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DOM Manipulation</title>

  <style>
    .highlight {
      color: blue;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h2 id="heading">Original Heading</h2>
  <p id="message">Original message</p>
  <a id="link" href="https://example.com">Visit website</a>

  <button id="updateButton">Update Page</button>

  <script>
    const heading = document.querySelector("#heading");
    const message = document.querySelector("#message");
    const link = document.querySelector("#link");
    const button = document.querySelector("#updateButton");

    button.addEventListener("click", function () {
      heading.textContent = "Updated Heading";
      message.innerHTML = "<strong>Content updated!</strong>";

      link.setAttribute("href", "https://web4learners.com");
      link.textContent = "Visit Web4Learners";

      heading.style.fontSize = "30px";
      message.classList.add("highlight");
    });
  </script>
</body>
</html>

When the user clicks Update Page, JavaScript:

  • Changes the heading using textContent.
  • Inserts bold HTML using innerHTML.
  • Updates the link destination using setAttribute().
  • Changes the heading’s font size using style.
  • Adds the highlight class to the message.

This example demonstrates how different DOM manipulation techniques work together to create an interactive webpage.

Frequently Asked Questions

What is the difference between textContent and innerHTML?

textContent treats assigned content as text, while innerHTML parses assigned content as HTML markup. Use textContent for plain text and use innerHTML only when inserting HTML is necessary and the content is trusted or sanitized.

What is the difference between textContent and innerText?

textContent returns text from an element and its descendants, including hidden descendant text. innerText generally returns rendered text and considers CSS visibility and layout.

How do I change an HTML attribute in JavaScript?

Use setAttribute() to create or update an attribute. Use getAttribute() to read it, removeAttribute() to remove it, and hasAttribute() to check whether it exists.

How do I change CSS styles using JavaScript?

Select the element and update its style property, such as element.style.color = "blue". CSS properties with hyphens generally use camelCase when accessed through style.

How do I add or remove a class in JavaScript?

Use element.classList.add("className") to add a class and element.classList.remove("className") to remove it. You can also use toggle() and contains().

Is classList better than changing the class attribute?

For individual class changes, classList is usually more convenient because it allows you to add, remove, toggle, or check a class without replacing other classes on the element.

Conclusion

JavaScript provides several ways to change HTML elements dynamically. Use textContent for plain text, innerHTML for HTML markup, and innerText when you need rendered text. Use attribute methods to update element attributes, the style property to modify inline CSS, and classList to manage CSS classes.

Understanding these techniques helps you manipulate the DOM, build interactive webpages, and create dynamic user interfaces with JavaScript.