JAVASCRIPT
Update Element Text and HTML Content
Learn how to dynamically change the visible text and raw HTML content of any existing DOM element using JavaScript's textContent and innerHTML properties.
const myElement = document.getElementById('myParagraph');
myElement.textContent = 'New plain text content.';
const anotherElement = document.querySelector('.html-container');
anotherElement.innerHTML = '<strong>New HTML content</strong> with a <span style="color: blue;">blue span</span>.';
// Example HTML setup (not part of snippet, but for context):
// <p id="myParagraph">Original text here.</p>
// <div class="html-container">Original <em>HTML</em> content.</div>
How it works: This snippet demonstrates how to modify the content of existing DOM elements. `textContent` sets or returns the text content of the specified node and its descendants, effectively stripping any HTML tags. `innerHTML` sets or returns the HTML content (markup) of an element, allowing you to inject or modify HTML structure within an element. Be cautious with `innerHTML` when using untrusted input to prevent XSS vulnerabilities.