JAVASCRIPT

Update Element Content Safely and Dynamically

Efficiently update an HTML element's text-only or rich HTML content using `textContent` for security and `innerHTML` for dynamic layouts, understanding their key differences.

function updateElementContent(elementId, type) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return;
    }

    if (type === 'text') {
        // Using textContent is safer as it treats all input as plain text
        const newText = "This is <b>plain text</b>. HTML tags are escaped.";
        element.textContent = newText;
        console.log("Content updated with textContent:", element.textContent);
    } else if (type === 'html') {
        // Using innerHTML allows rendering of HTML tags, but can be a security risk (XSS)
        const newHtml = "This is <b>rich HTML</b> content. <span style='color: green;'>Styled!</span>";
        element.innerHTML = newHtml;
        console.log("Content updated with innerHTML:", element.innerHTML);
    } else {
        console.warn("Invalid type. Use 'text' or 'html'.");
    }
}

// Example usage:
// Assume HTML: <div id="contentArea" style="border: 1px solid #ccc; padding: 10px;">Original content.</div>
//
// Update with plain text:
// updateElementContent('contentArea', 'text');
//
// Update with HTML (be cautious of XSS when using user-provided input with innerHTML):
// setTimeout(() => updateElementContent('contentArea', 'html'), 2000);
How it works: The `textContent` and `innerHTML` properties are fundamental for modifying the content of DOM elements. `textContent` sets or returns the text content of a node and its descendants, treating any HTML tags within the string as literal text, making it safe from Cross-Site Scripting (XSS) attacks when dealing with user-generated input. Conversely, `innerHTML` sets or returns the HTML content, parsing and rendering any HTML tags provided. While `innerHTML` is powerful for dynamic layouts, it should be used with caution, especially with untrusted input, due to potential security vulnerabilities. Always prefer `textContent` if you only need to update plain text.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs