
AgnosticStyles is a JavaScript utility that applies CSS styles or class changes to a DOM element safely, only if the element exists.
This utility can be useful in several situations. Consider dynamic content loading, where elements might appear after the initial page load. Or perhaps you’re working with a single-page application and need to manage style changes as the user interacts with different components.
AgnosticStyles provides a safeguard against common DOM manipulation problems in these scenarios. It avoids errors and allows you to implement style changes without constantly checking if an element exists. The built-in debugging flags offer more control over tracking style and class manipulations, aiding in development and troubleshooting.
How to use it:
1. Install AgnosticStyles with NPM.
# NPM $ npm install agnostic-styles
2. Import the agnosticStyles function into your web project and configure it with your desired debug options:
import { agnosticStyles } from 'agnostic-styles';window.agnosticStyles = agnosticStyles({
debugLog: true,
debugWarn: true,
});3. Add one or more classes to a specified element.
window.safeClassAdd = window.agnosticStyles('addClass', 'customClass');
// OR
window.safeClassAdd = window.agnosticStyles('addClass', ['customClass1', 'customClass2', 'customClass3']);
// Apply the CSS class(es) to the target element
safeClassAdd('element-id');4. Remove one or more classes from the element.
window.safeClassRemove = window.agnosticStyles('removeClass', 'customClass');
// OR
window.safeClassAdd = window.agnosticStyles('removeClass', ['customClass1', 'customClass2', 'customClass3']);
// Remove the CSS class(es) from the target element
safeClassRemove('element-id');5. Set inline CSS styles on an element.
window.safeStyleChange = window.agnosticStyles('setStyle', { color: 'white' });
safeStyleChange('element-id');6. Remove inline CSS styles from the element.
window.safeStyleRemove = window.agnosticStyles('removeStyle', ['color']);
safeStyleRemove('element-id');






