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
innerHTMLwith 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
textContentoverinnerHTMLwhen handling plain text to avoid potential security risks. - Avoid inline styling. Use CSS classes instead, toggling them with
classListto 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
- Modifying Text Content
- Objective: Practice using
textContent. - Instructions: Create an HTML file with a
<p>element withid="message". Use JavaScript to select the paragraph and change its text to"Hello, JavaScript!".
- Objective: Practice using
- Inserting HTML with
innerHTML- Objective: Use
innerHTMLto modify HTML structure. - Instructions: Create an empty
<div>withid="content". Use JavaScript to insert an<h1>and a<p>with sample text inside thecontentdiv.
- Objective: Use
- Modifying Attributes with
setAttribute- Objective: Practice changing attributes.
- Instructions: Add an
<img>element withid="thumbnail"and set its initialsrcattribute to"default.jpg". Use JavaScript to change thesrcto"new-image.jpg".
- Toggling Classes with
classList- Objective: Use
classListto dynamically manage classes. - Instructions: Create a
<button>withid="toggleButton". Write JavaScript to toggle a"highlight"class on the button each time it’s clicked.
- Objective: Use
- Removing Attributes Dynamically
- Objective: Practice using
removeAttribute. - Instructions: Add a
<button>withid="submitButton"and set thedisabledattribute. Use JavaScript to remove thedisabledattribute, making the button clickable.
- Objective: Practice using
Multiple-Choice Questions
- Which property is used to set or retrieve the plain text content of an element?
- A)
innerHTMLB)textContentC)setAttributeD)innerText
textContentis used to set or retrieve plain text content. - A)
- What will the following code output?javascriptCopy code
const 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>
Hello, astextContentretrieves only the text content, ignoring HTML tags. - A)
- Which method would you use to add an attribute to an element?
- A)
getAttributeB)removeAttributeC)addAttributeD)setAttribute
setAttributeis used to add or change an attribute on an element. - A)
- 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")
element.classList.toggle("className")toggles the specified class on or off. - A)
- What does
removeAttribute("disabled")do on a button element?- A) Enables the button by removing the
disabledattributeB) Disables the button by settingdisabledtofalseC) Hides the buttonD) Deletes the button from the DOM
removeAttribute("disabled")enables the button by removing thedisabledattribute. - A) Enables the button by removing the
