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:

  1. Select target elements: querySelectorAll('.my-main-div-class span') finds all span elements within the main div
  2. Get source text: getElementsByClassName('uniqueId')[0].textContent extracts text from the h2 element
  3. 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.

My Name is John Div Container: My Name is John My Name is John My Name is John

Key Points

  • querySelectorAll() returns a NodeList of all matching elements
  • getElementsByClassName() returns a live HTMLCollection
  • Use textContent to 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.

Updated on: 2026-03-15T23:18:59+05:30

876 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements