Using textContent in JavaScript DOM (Live Playground)
In this tutorial, we will learn how to use the textContent
property in JavaScript to access and manipulate the text content of a given HTML element in the DOM. We'll cover the basics of the textContent property and provide sample code with explanations.
What is textContent?
The textContent
property is a built-in JavaScript DOM property that allows you to access and manipulate the text content of a given HTML element. The textContent
property returns a string containing the text content of the element, and you can also set the text content of an element by assigning a new value to the textContent
property.
Sample Code: Using textContent
Let's say we have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>textContent Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>
To use textContent
to access and manipulate the text content of an element, you'll need to include a JavaScript <script>
tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.
Here's how you can access the text content of the h1
element with the class mainHeading
and change its content:
<!DOCTYPE html>
<html>
<head>
<title>textContent Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
<script>
// Select the element with the class "mainHeading"
var mainHeading = document.querySelector('.mainHeading');
// Access its text content
console.log('Original content:', mainHeading.textContent);
// Modify the text content
mainHeading.textContent = 'New Heading Text';
// Verify the changes
console.log('Updated content:', mainHeading.textContent);
</script>
</body>
</html>
After running this code, the text content of the h1
element with the class mainHeading
will be changed to "New Heading Text".
Conclusion
The textContent
property is a useful tool for accessing and manipulating the text content of a given HTML element in the DOM. By mastering this property, you can easily change the text content of your web pages dynamically, allowing you to create interactive and engaging web experiences.