JAVASCRIPT

Dynamically Update DOM Element Attributes and Styles

Discover how to programmatically change HTML attributes like `id` or `src`, add/remove CSS classes, and modify inline styles of DOM elements.

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

  // Update text content
  if (newText !== undefined) {
    element.textContent = newText;
  }

  // Manage classes
  if (newClass) {
    // Example: Toggle or replace classes
    element.classList.toggle('highlight'); // Toggle 'highlight' class
    // element.classList.add(newClass); // Add a specific class
    // element.classList.remove('old-class'); // Remove a specific class
    // element.className = newClass; // Replace all classes
  }

  // Update inline styles
  if (newStyle) {
    // newStyle should be an object, e.g., { color: 'red', fontSize: '18px' }
    for (const prop in newStyle) {
      if (newStyle.hasOwnProperty(prop)) {
        element.style[prop] = newStyle[prop];
      }
    }
  }

  // Example of updating other attributes (e.g., src for img, href for a)
  // if (element.tagName === 'IMG' && element.id === 'myImage') {
  //   element.setAttribute('src', 'new-image.jpg');
  //   element.setAttribute('alt', 'New descriptive alt text');
  // }
}

// Example usage:
// Assume <p id="myParagraph" class="initial-class">Original text</p> in HTML

// updateElementProperties(
//   'myParagraph',
//   'Updated text content!',
//   'new-class', // This example uses classList.toggle for 'highlight'
//   { color: 'blue', border: '1px solid black' }
// );

/*
Expected HTML structure after execution (if initial class was not 'highlight'):
<p id="myParagraph" class="initial-class highlight" style="color: blue; border: 1px solid black;">Updated text content!</p>
*/
How it works: This snippet demonstrates how to modify various properties of an existing DOM element. The `updateElementProperties` function allows changing an element's text content, toggling CSS classes using `classList.toggle`, and applying inline styles. It also includes commented-out examples for adding/removing specific classes and setting other HTML attributes like `src` or `alt` for images, providing comprehensive control over element presentation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs