JAVASCRIPT

Update DOM Element Text, HTML, and Attributes

Learn to modify the text content, inner HTML, or specific attributes of an existing DOM element using vanilla JavaScript methods like `textContent`, `innerHTML`, `setAttribute`, and `removeAttribute`.

function updateElementContentAndAttrs(elementId, newText, newHtml, attributesToSet = {}, attributesToRemove = []) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return;
    }

    // Update text content (safer, prevents XSS if only text is needed)
    if (newText !== undefined) {
        element.textContent = newText;
    }

    // Update inner HTML (use with caution for user-generated content due to XSS risk)
    if (newHtml !== undefined) {
        element.innerHTML = newHtml;
    }

    // Set new attributes
    for (const key in attributesToSet) {
        if (Object.hasOwnProperty.call(attributesToSet, key)) {
            element.setAttribute(key, attributesToSet[key]);
        }
    }

    // Remove attributes
    attributesToRemove.forEach(attr => {
        element.removeAttribute(attr);
    });
}

// Example Usage:
// <p id="myParagraph" data-original="yes" class="old-class">Hello World</p>
// updateElementContentAndAttrs('myParagraph', 'Updated Text Content!', undefined, { class: 'new-class', title: 'Tooltip' }, ['data-original']);
// updateElementContentAndAttrs('myParagraph', undefined, '<strong>New HTML!</strong>');
// updateElementContentAndAttrs('myParagraph', 'Final plain text!');
How it works: This snippet demonstrates how to modify an existing DOM element. You can update its plain text content using `textContent` (safe against XSS for pure text), or its inner HTML structure using `innerHTML` (use carefully with untrusted input due to potential XSS vulnerabilities). Additionally, it shows how to `setAttribute` to add or change attributes and `removeAttribute` to delete them, providing comprehensive control over element properties.

Need help integrating this into your project?

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

Hire DigitalCodeLabs