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
overinnerHTML
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
- 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
innerHTML
to modify HTML structure. - Instructions: Create an empty
<div>
withid="content"
. Use JavaScript to insert an<h1>
and a<p>
with sample text inside thecontent
div.
- Objective: Use
- Modifying Attributes with
setAttribute
- Objective: Practice changing attributes.
- Instructions: Add an
<img>
element withid="thumbnail"
and set its initialsrc
attribute to"default.jpg"
. Use JavaScript to change thesrc
to"new-image.jpg"
.
- Toggling Classes with
classList
- Objective: Use
classList
to 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 thedisabled
attribute. Use JavaScript to remove thedisabled
attribute, 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)
innerHTML
B)textContent
C)setAttribute
D)innerText
textContent
is 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)
Hello
B)<strong>Hello</strong>
C)<strong>
D)Hello<strong></strong>
Hello
, astextContent
retrieves only the text content, ignoring HTML tags. - A)
- Which method would you use to add an attribute to an element?
- A)
getAttribute
B)removeAttribute
C)addAttribute
D)setAttribute
setAttribute
is 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
disabled
attributeB) Disables the button by settingdisabled
tofalse
C) Hides the buttonD) Deletes the button from the DOM
removeAttribute("disabled")
enables the button by removing thedisabled
attribute. - A) Enables the button by removing the
