Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Replace HTML div into text element with JavaScript?
To replace HTML div content with text from another element, you can use document.querySelectorAll() to select multiple elements and getElementsByClassName() to get the source text. This approach allows you to dynamically update multiple elements with content from a single source.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace Div Content</title>
</head>
<body>
<h2 class="uniqueId">My Name is John</h2>
<div class="my-main-div-class">
<div class="div-class-2">
<span>My h2 value must be here...</span>
</div>
<div class="div-class-end">
<span>My h2 value must be here...</span>
<span>My h2 value must be here...</span>
</div>
</div>
<script>
// Get all span elements inside the main div
const allSpan = document.querySelectorAll('.my-main-div-class span');
// Get the text content from the source element
const replaceText = document.getElementsByClassName('uniqueId')[0].textContent;
// Replace text content in all spans
for (let element of allSpan) {
element.textContent = replaceText;
}
</script>
</body>
</html>
How It Works
The code follows these steps:
-
Select target elements:
querySelectorAll('.my-main-div-class span')finds all span elements within the main div -
Get source text:
getElementsByClassName('uniqueId')[0].textContentextracts text from the h2 element -
Replace content: The for loop iterates through each span and updates its
textContent
Alternative Using querySelector
You can also use querySelector for the source element:
<script>
const allSpan = document.querySelectorAll('.my-main-div-class span');
const replaceText = document.querySelector('.uniqueId').textContent;
allSpan.forEach(element => {
element.textContent = replaceText;
});
</script>
Output
After running the script, all span elements will display "My Name is John" instead of their original placeholder text.
Key Points
-
querySelectorAll()returns a NodeList of all matching elements -
getElementsByClassName()returns a live HTMLCollection - Use
textContentto safely set plain text content - The for...of loop provides clean iteration over the NodeList
Conclusion
This method efficiently replaces content in multiple elements using DOM selection methods. querySelectorAll() combined with getElementsByClassName() provides flexible element targeting for dynamic content updates.
Advertisements
