JAVASCRIPT

Update Element Content and Attributes

Discover how to efficiently modify the text content, inner HTML, and various attributes (like class or data-*) of existing DOM elements using vanilla JavaScript.

function updateElement(selector, newTextContent, newHTMLContent = '', attributes = {}) {
    const element = document.querySelector(selector);
    if (!element) {
        console.error('Element not found:', selector);
        return;
    }

    if (newTextContent !== null) {
        element.textContent = newTextContent;
    }

    if (newHTMLContent) {
        element.innerHTML = newHTMLContent;
    }

    for (const key in attributes) {
        if (key === 'class') {
            element.className = attributes[key]; // Directly set class string
        } else if (key === 'addClass') {
            element.classList.add(...attributes[key].split(' ')); // Add multiple classes
        } else if (key === 'removeClass') {
            element.classList.remove(...attributes[key].split(' ')); // Remove multiple classes
        } else if (key === 'toggleDataAttribute') {
            const dataKey = attributes[key];
            if (element.dataset[dataKey]) {
                delete element.dataset[dataKey];
            } else {
                element.dataset[dataKey] = 'true';
            }
        } else if (key.startsWith('data-')) {
            element.setAttribute(key, attributes[key]); // Set data-attributes
        } else {
            element.setAttribute(key, attributes[key]); // Set other attributes
        }
    }
}

// Usage example:
// <p id="myParagraph" data-status="pending" class="message"></p>

updateElement('#myParagraph', 'Content updated!', null, {
    addClass: 'success important',
    removeClass: 'message',
    'data-status': 'completed',
    style: 'color: green;',
    title: 'Updated paragraph'
});

// Update with inner HTML
updateElement('#myParagraph', null, '<strong>HTML</strong> content updated!', {
    'data-count': '10'
});

// Toggle a data attribute
updateElement('#myParagraph', null, null, {
    toggleDataAttribute: 'expanded'
});
How it works: This snippet provides a versatile function to update an existing DOM element. It allows changing the element's `textContent` or `innerHTML` and dynamically modifying its attributes. It includes handling for setting, adding, or removing CSS classes, and also demonstrates how to manipulate custom `data-*` attributes, providing fine-grained control over element presentation and behavior.

Need help integrating this into your project?

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

Hire DigitalCodeLabs