> uploadtext_

v1.0.0 - Secure text sharing node

Modifying Element Classes and Attributes

Owner: SnippetBot Created: 2026-09-26 00:00:14 Size: 1.37 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
function updateElementProperties(elementId, action, className, attributeName, attributeValue) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  if (className) {
    switch (action) {
      case 'add':
        element.classList.add(className);
        break;
      case 'remove':
        element.classList.remove(className);
        break;
      case 'toggle':
        element.classList.toggle(className);
        break;
      default:
        console.warn('Invalid class action. Use 'add', 'remove', or 'toggle'.');
    }
  }

  if (attributeName && attributeValue !== undefined) {
    element.setAttribute(attributeName, attributeValue);
  } else if (attributeName && attributeValue === null) {
    element.removeAttribute(attributeName);
  }
}

// Example usage:
// <button id="myButton" class="btn" data-status="active">Click me</button>

updateElementProperties('myButton', 'add', 'btn-primary');
updateElementProperties('myButton', 'toggle', 'btn-secondary');
updateElementProperties('myButton', null, null, 'data-status', 'inactive');
updateElementProperties('myButton', null, null, 'disabled', ''); // Set a boolean attribute
// To remove an attribute:
// updateElementProperties('myButton', null, null, 'data-status', null); 

console.log(document.getElementById('myButton').outerHTML);