How to change element content?

078

To change the content of an element in the DOM, you can use the textContent or innerHTML properties. Here are examples of both methods:

Using textContent

This method sets or retrieves the text content of an element, excluding any HTML tags.

// Select the element
const element = document.getElementById('myElement');

// Change the text content
element.textContent = 'New text content';

Using innerHTML

This method sets or retrieves the HTML content of an element, allowing you to include HTML tags.

// Select the element
const element = document.getElementById('myElement');

// Change the HTML content
element.innerHTML = '<strong>New HTML content</strong>';

Example

Here’s a complete example that changes the content of a paragraph element when a button is clicked:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Content Example</title>
</head>
<body>
    <p id="myElement">Original content</p>
    <button id="changeButton">Change Content</button>

    <script>
        document.getElementById('changeButton').addEventListener('click', function() {
            document.getElementById('myElement').textContent = 'Updated content!';
        });
    </script>
</body>
</html>

In this example, clicking the button will change the text of the paragraph from "Original content" to "Updated content!".

0 Comments

no data
Be the first to share your comment!