Learn how to manipulate content and attributes in the DOM using JavaScript, including textContent, innerText, innerHTML, and attribute methods.
In this section, we will explore how to manipulate content and attributes within the Document Object Model (DOM) using JavaScript. This is a crucial skill for creating dynamic and interactive web pages. By the end of this chapter, you’ll be able to change text, update HTML content, and modify attributes of HTML elements with confidence.
Before we dive into manipulating content and attributes, let’s briefly recap what the DOM is. The DOM is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes, where each node is an object representing a part of the document.
One of the simplest ways to manipulate the DOM is by changing the text content of an element. JavaScript provides several properties and methods to do this, including textContent and innerText.
textContentThe textContent property is used to get or set the text content of an element and its descendants. It includes all text, even if the element is hidden with CSS.
// Select the element
let paragraph = document.querySelector('#myParagraph');
// Get the current text content
console.log(paragraph.textContent);
// Set new text content
paragraph.textContent = 'This is the new text content!';
Key Points:
textContent retrieves all text within an element, including hidden elements.textContent will replace all existing child nodes with a single text node.innerTextThe innerText property is similar to textContent, but it respects the styling of the text, such as display: none or visibility: hidden.
// Select the element
let paragraph = document.querySelector('#myParagraph');
// Get the current inner text
console.log(paragraph.innerText);
// Set new inner text
paragraph.innerText = 'This is the new inner text!';
Key Points:
innerText retrieves only the visible text within an element.textContent because it triggers a reflow to ensure the text is visible.innerHTMLThe innerHTML property allows you to get or set the HTML content of an element. This is powerful but comes with safety concerns.
// Select the element
let container = document.querySelector('#myContainer');
// Get the current HTML content
console.log(container.innerHTML);
// Set new HTML content
container.innerHTML = '<p>This is a new paragraph with <strong>bold</strong> text!</p>';
Safety Concerns:
innerHTML can introduce security vulnerabilities, such as Cross-Site Scripting (XSS), if the content is not properly sanitized.innerHTML can be slower than other methods because it re-parses the entire content of the element.Best Practices:
innerHTML with user-generated content unless you sanitize it first.textContent or innerText when only text needs to be updated.Attributes provide additional information about HTML elements. JavaScript provides methods to manipulate these attributes.
setAttribute() and getAttribute()The setAttribute() method is used to set the value of an attribute on an element, while getAttribute() retrieves the value of an attribute.
// Select the image element
let image = document.querySelector('#myImage');
// Get the current 'src' attribute
let srcValue = image.getAttribute('src');
console.log(srcValue);
// Set a new 'src' attribute
image.setAttribute('src', 'newImage.jpg');
Key Points:
getAttribute() retrieves the current value of an attribute.setAttribute() sets a new value for an attribute.In addition to setAttribute() and getAttribute(), you can directly access and modify attributes using properties.
// Select the image element
let image = document.querySelector('#myImage');
// Get the current 'src' attribute
console.log(image.src);
// Set a new 'src' attribute
image.src = 'anotherImage.jpg';
Key Points:
setAttribute() and getAttribute() are sometimes necessary.Let’s put these concepts into practice with a few examples.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change Text Content</title>
</head>
<body>
<p id="myParagraph">Original text content.</p>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
let paragraph = document.querySelector('#myParagraph');
paragraph.textContent = 'This is the updated text content!';
}
</script>
</body>
</html>
Explanation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update HTML Content</title>
</head>
<body>
<div id="myContainer">
<p>Original paragraph.</p>
</div>
<button onclick="updateHTML()">Update HTML</button>
<script>
function updateHTML() {
let container = document.querySelector('#myContainer');
container.innerHTML = '<p>New paragraph with <strong>bold</strong> text!</p>';
}
</script>
</body>
</html>
Explanation:
div with new HTML when the button is clicked.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Modify Attributes</title>
</head>
<body>
<img id="myImage" src="original.jpg" alt="Original Image">
<button onclick="changeImage()">Change Image</button>
<script>
function changeImage() {
let image = document.querySelector('#myImage');
image.setAttribute('src', 'newImage.jpg');
image.alt = 'New Image';
}
</script>
</body>
</html>
Explanation:
src and alt attributes of the image when the button is clicked.Experiment with the examples provided. Try changing the text, HTML, and attributes to see how the DOM updates in real time. Here are some suggestions:
innerHTML to add new elements dynamically.To better understand how the DOM is structured, let’s visualize it using a simple DOM tree diagram:
graph TD;
A[Document]
B[html]
C[head]
D[body]
E[div]
F[p]
G[img]
A --> B
B --> C
B --> D
D --> E
E --> F
E --> G
Diagram Explanation:
Document node.html element is a child of the Document.head and body elements are children of html.div element is a child of body, containing a p and an img element.In this section, we’ve learned how to manipulate content and attributes in the DOM using JavaScript. We explored:
textContent and innerText.innerHTML and understanding the associated safety concerns.setAttribute() and getAttribute(), as well as direct property access.By mastering these techniques, you can create dynamic and interactive web pages that respond to user actions.