Modifying Content and Attributes in the DOM using JavaScript


Introduction

JavaScript provides a powerful set of methods and properties to modify the content and attributes of DOM elements. These techniques are essential for creating dynamic web applications, enabling developers to update text, HTML content, and attributes on the fly. This chapter covers methods such as textContent, innerHTML, and setAttribute, along with best practices for using these methods effectively and securely.


1. Modifying Text Content: textContent

The textContent property is used to set or get the plain text content of an element. Unlike innerHTML, textContent does not interpret HTML tags, so it’s faster and more secure when dealing with plain text.

Syntax

element.textContent = "New text content";
  • Assigning a Value: Sets the element’s text content to the specified value.
  • Getting a Value: Retrieves the current text content of the element.

Example

<p id="greeting">Hello, world!</p>
<script>
const greeting = document.getElementById("greeting");
greeting.textContent = "Hello, JavaScript!";
</script>

In this example, textContent updates the text inside the <p> element with id="greeting" to "Hello, JavaScript!".


2. Modifying HTML Content: innerHTML

The innerHTML property is used to get or set the HTML content of an element. Unlike textContent, innerHTML interprets and renders HTML tags, allowing you to insert HTML elements and structure within an element.

Syntax

element.innerHTML = "<strong>Bold text</strong>";
  • Assigning a Value: Replaces the entire HTML content of the element with the specified HTML string.
  • Getting a Value: Retrieves the HTML markup of the element’s contents.

Example

<div id="container"></div>
<script>
const container = document.getElementById("container");
container.innerHTML = "<h2>Welcome!</h2><p>Thank you for visiting our site.</p>";
</script>

In this example, innerHTML inserts an <h2> heading and a <p> paragraph into the container div.

Note: Avoid using innerHTML with user-generated content to prevent cross-site scripting (XSS) vulnerabilities.


3. Modifying Attributes: setAttribute and getAttribute

The setAttribute and getAttribute methods are used to manipulate an element’s attributes, such as href, src, class, and id.

  • setAttribute(attributeName, value): Sets the specified attribute to a new value.
  • getAttribute(attributeName): Gets the current value of the specified attribute.

Syntax

element.setAttribute("attributeName", "value");
const value = element.getAttribute("attributeName");

Example

<a id="link" href="https://example.com">Visit Example</a>
<script>
const link = document.getElementById("link");
link.setAttribute("href", "https://newsite.com");
console.log(link.getAttribute("href")); // Output: https://newsite.com
</script>

In this example, setAttribute changes the href attribute of the anchor element to "https://newsite.com".


4. Directly Modifying Attributes with Properties

Some attributes can also be modified directly using properties. For example, you can set an element’s id, src, href, value, or className without setAttribute.

Example

<img id="logo" src="logo.png" alt="Logo">
<script>
const logo = document.getElementById("logo");
logo.src = "new-logo.png";
logo.alt = "New Logo";
</script>

Here, src and alt are modified directly as properties on the logo element.


5. Removing Attributes: removeAttribute

The removeAttribute method removes a specified attribute from an element, which can be useful for dynamically adjusting the behavior or appearance of an element.

Syntax

element.removeAttribute("attributeName");

Example

<button id="myButton" disabled>Click me</button>
<script>
const myButton = document.getElementById("myButton");
myButton.removeAttribute("disabled");
</script>

In this example, removeAttribute removes the disabled attribute from the button, making it clickable.


6. Modifying Class Names: classList

The classList property provides methods to manipulate the classes of an element, such as adding, removing, toggling, and checking if a class is present.

  • classList.add("className"): Adds a class to the element.
  • classList.remove("className"): Removes a class from the element.
  • classList.toggle("className"): Toggles the class on or off.
  • classList.contains("className"): Checks if the element has the specified class.

Example

<div id="box" class="highlight"></div>
<script>
const box = document.getElementById("box");
box.classList.add("shadow");
box.classList.toggle("highlight");
console.log(box.classList.contains("shadow")); // Output: true
</script>

Here, classList adds a class "shadow" and toggles the "highlight" class on the box element.


7. Best Practices for Modifying Content and Attributes

  • Use textContent over innerHTML when handling plain text to avoid potential security risks.
  • Avoid inline styling. Use CSS classes instead, toggling them with classList to manage styles dynamically.
  • Cache frequently accessed elements: Avoid redundant DOM selections by storing elements in variables, especially when modifying content or attributes multiple times.

Exercises


  1. Modifying Text Content
    • Objective: Practice using textContent.
    • Instructions: Create an HTML file with a <p> element with id="message". Use JavaScript to select the paragraph and change its text to "Hello, JavaScript!".
  2. Inserting HTML with innerHTML
    • Objective: Use innerHTML to modify HTML structure.
    • Instructions: Create an empty <div> with id="content". Use JavaScript to insert an <h1> and a <p> with sample text inside the content div.
  3. Modifying Attributes with setAttribute
    • Objective: Practice changing attributes.
    • Instructions: Add an <img> element with id="thumbnail" and set its initial src attribute to "default.jpg". Use JavaScript to change the src to "new-image.jpg".
  4. Toggling Classes with classList
    • Objective: Use classList to dynamically manage classes.
    • Instructions: Create a <button> with id="toggleButton". Write JavaScript to toggle a "highlight" class on the button each time it’s clicked.
  5. Removing Attributes Dynamically
    • Objective: Practice using removeAttribute.
    • Instructions: Add a <button> with id="submitButton" and set the disabled attribute. Use JavaScript to remove the disabled attribute, making the button clickable.

Multiple-Choice Questions


  1. Which property is used to set or retrieve the plain text content of an element?
    • A) innerHTMLB) textContentC) setAttributeD) innerText
    Answer: B. textContent is used to set or retrieve plain text content.
  2. What will the following code output?javascriptCopy codeconst para = document.createElement("p"); para.innerHTML = "<strong>Hello</strong>"; document.body.appendChild(para); console.log(para.textContent);
    • A) HelloB) <strong>Hello</strong>C) <strong>D) Hello<strong></strong>
    Answer: A. Hello, as textContent retrieves only the text content, ignoring HTML tags.
  3. Which method would you use to add an attribute to an element?
    • A) getAttributeB) removeAttributeC) addAttributeD) setAttribute
    Answer: D. setAttribute is used to add or change an attribute on an element.
  4. What is the correct way to toggle a class on an element?
    • A) element.classList.add("className")B) element.classList.toggle("className")C) element.className += "className"D) element.toggle("className")
    Answer: B. element.classList.toggle("className") toggles the specified class on or off.
  5. What does removeAttribute("disabled") do on a button element?
    • A) Enables the button by removing the disabled attributeB) Disables the button by setting disabled to falseC) Hides the buttonD) Deletes the button from the DOM
    Answer: A. removeAttribute("disabled") enables the button by removing the disabled attribute.