DOM Element Content
The ability to work with the text or HTML in a web page requires an understanding of the DOM. JavaScript allows you to choose and work with the DOM to create interactive, as opposed to static, web pages. You can modify your website in reaction to user behaviour by manipulating dynamic elements. It is no longer a static event because DOM manipulation enables a variety of interactions with the web page.
Accessing Elements in the DOM
You must locate or “select” an element before you can work with its content. For this, the document object has numerous properties and functions. There are several ways to choose elements from the DOM. Some common methods for accessing elements include: getElementById(), getElementsByTagName(), getElementsByClassName(), querySelector() and querySelectorAll()
Manipulating Element Content
You can change an element once you’ve chosen it. The same way that a variable’s contents can be altered, so can content. You may view and change an element’s content using a number of properties:
- innerText: This attribute is concerned with the text that appears between the element’s opening and closing tags. It addresses how an element’s content is represented in plain text. You can edit the text that appears inside an element by modifying innerText.
- innerHTML: Everything that is between the element’s starting and ending tags is contained in this property. It deals with how the content of an element is represented in HTML strings. The browser parses the supplied HTML string when setting innerHTML, then generates new DOM nodes in accordance. This is a handy approach to add a section of HTML since it lets you put HTML markup inside an element.
- textContent: You can view and modify the element’s content using this attribute. TextContent delivers just text data and removes all HTML tags, just like innerText does.
- nodeValue: Text nodes’ content is stored in this field. NodeValue is primarily used for the text content inside a text node, whereas innerText or textContent are usually used for elements.
Here are some code samples that show you how to use JavaScript to pick an element and modify its content:
We have the following simple HTML structure:
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>DOM Content Modification Samples</title>
</head>
<body>
<h1 id=”main-title”>Original Title</h1>
<p class=”intro-text”>This is the first paragraph.</p>
<p class=”intro-text”>This is the second paragraph with a <strong>bold word</strong>.</p>
<div id=”content-area”>
<h2>Section Heading</h2>
<p>Some initial text inside the div.</p>
<span id=”nested-span”>Nested content here.</span>
</div>
<p id=”message-paragraph”>Simple message.</p>
<script>
// It’s good practice to ensure the DOM is fully loaded before
// trying to access elements. window.onload or DOMContentLoaded
// events are typically used for this. This example assumes the script
// is placed at the end of the body, ensuring elements above it exist.
// — Sample 1: Using textContent —
// Select the h1 element by its ID
const mainTitleElement = document.getElementById(‘main-title’);
console.log(‘Selected h1 element:’, mainTitleElement); // Log the selected element
// Modify its plain text content using textContent
// Any existing HTML inside (like <em>) would be removed
mainTitleElement.textContent = ‘Updated Title using textContent!’;
console.log(‘h1 textContent updated.’);
// — Sample 2: Using innerHTML —
// Select the div element by its ID
const contentAreaElement = document.getElementById(‘content-area’);
console.log(‘Selected div element:’, contentAreaElement);
// Modify its HTML content using innerHTML
// This replaces everything inside the div with new HTML
contentAreaElement.innerHTML = ‘<h3>New Section</h3><p>Content replaced with <strong>new HTML</strong>!</p>’;
console.log(‘Div innerHTML updated.’);
// — Sample 3: Using innerText —
// Select the paragraph with ID ‘message-paragraph’
const messageParagraphElement = document.getElementById(‘message-paragraph’);
console.log(‘Selected message paragraph:’, messageParagraphElement);
// Modify its plain text content using innerText
messageParagraphElement.innerText = ‘This message was updated using innerText.’;
console.log(‘Message paragraph innerText updated.’);
// Note: For collections (like from getElementsByClassName or querySelectorAll)
// you need to iterate through the collection to modify each element.
// Example using querySelectorAll and innerHTML
// const introParagraphs = document.querySelectorAll(‘.intro-text’);
// introParagraphs.forEach(p => {
// p.innerHTML = ‘<em>Intro paragraph modified!</em>’;
// });
// — Sample 4: Using nodeValue (requires targeting a text node child) —
// Select the message paragraph again
const pForNodeValue = document.getElementById(‘message-paragraph’);
console.log(‘Selected paragraph for nodeValue:’, pForNodeValue);
// nodeValue is for Text nodes, not Element nodes.
// To change the text content using nodeValue, we need to get the actual Text node inside the paragraph.
// We assume the first child of the paragraph is the text node we want to change.
const textNode = pForNodeNodeValue.firstChild; // Get the first child node
console.log(‘Selected text node child:’, textNode);
// Check if the first child is actually a Text node (nodeType === 3)
if (textNode && textNode.nodeType === 3) {
// Modify the text node’s value using nodeValue
textNode.nodeValue = ‘Text modified using nodeValue on the text node child!’;
console.log(‘Text node value updated.’);
} else {
console.log(‘First child is not a text node or not found. Cannot modify nodeValue directly.’);
}
</script>
</body>
</html>
Creating and Adding New Elements with Content
Adding new components to the page is a common practice for dynamic content. Usually, to do this, a new element must be created, its content set, and then it is added to an existing element in the DOM tree.
function addOne() {
// Get value from input field
var a = document.getElementById(“addItem”).value;
// Create a new li element
var li = document.createElement(“li”);
// Create a text node with the input value and append it to the li
li.appendChild(document.createTextNode(a));
// Append the new li element to the ol list with id “sList”
document.getElementById(“sList”).appendChild(li);
}
You may develop contemporary, engaging user experiences on web sites by becoming proficient in these techniques for choosing and modifying element content.