Explain Codes LogoExplain Codes Logo

Remove Style on Element

javascript
style-removal
event-listening
dom-manipulation
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR

Remove inline styles from an HTML element swiftly and cleanly using pure JavaScript:

// Wipe away all inline styles; poof! Styles be gone! document.getElementById('elementId').style.cssText = ''; // Or remove a specific style property: document.getElementById('elementId').style.color = '';

Removing specific inline styles

If you want to eliminate specific styles and leave the rest intact, no worries; we've got you covered:

let element = document.getElementById('elementId'); element.style.removeProperty('width'); // Width is binary; it's either there, or it's *width*out. element.style.removeProperty('height'); // Height be gone! // for our parents' IE, the good old way element.style.width = ''; element.style.height = ''; // Treats height like my ex; it's like it never existed.

Now, the width and height styles have been given a one-way ticket out of your code.

Beating stubborn or external styles

Sometimes, styles are just as stubborn as mules, or you have to tackle external styles. We'll ambush them using regex:

let element = document.getElementById('elementId'); let stylesToRemove = ['width', 'height']; let newStyle = element.style.cssText.replace( new RegExp(stylesToRemove.join('|'), 'gi'), // RegExp? More like 'Really-expresses' your need! '' ); element.style.cssText = newStyle;

Here, we craftily match each persistent style and drop them like hot potatoes.

Resetting the default styles

Sometimes, you might just want to restore the default value of a style instead of removing it totally:

document.getElementById('elementId').style.setProperty('width', 'unset'); // Like a universal undo button for styles.

The omnipotent loop

Looping is not just for breakfast cereals! When you are dealing with multiple elements, the loop becomes your best ally:

Array.from(document.getElementsByClassName('remove-styles')).forEach(el => { el.style.cssText = ''; // Teamwork makes the dream work; working together to say bye-bye to all unwanted styles! });

Reapplying styles: Handle with care

After using removeAttribute("style"), remember to rehang the styles you want:

let element = document.getElementById('elementId'); element.removeAttribute('style'); // An extreme makeover // Bring back the styles that aren't fashion disasters! element.style.color = 'red';

Event handling: Timing is everything

Selecting the ideal event for attaching the style removal action will greatly enhance your solution. Here's a way to attach an event listener to your element:

document.getElementById('elementId').addEventListener('click', function() { this.style.cssText = ''; // Style doctor on call, now making house visits! });