Last active
August 18, 2020 21:03
-
-
Save nathansmith/262366 to your computer and use it in GitHub Desktop.
Remove inline styles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Remove inline style="..." | |
Preserve hidden content. | |
Call the function like this: | |
var all = document.getElementsByTagName('*'); | |
remove_style(all); | |
Note: Selecting all elements in the page via a | |
wildcard query could be slow, depending on how | |
many elements are in the page. You could use a | |
smaller set of elements to be more performant: | |
var set = document.getElementById('foo').getElementsByTagName('bar'); | |
remove_style(set); | |
*/ | |
function remove_style(list) { | |
'use strict'; | |
// Presentational attributes. | |
var attr = [ | |
'align', | |
'background', | |
'bgcolor', | |
'border', | |
'cellpadding', | |
'cellspacing', | |
'color', | |
'face', | |
'height', | |
'hspace', | |
'marginheight', | |
'marginwidth', | |
'noshade', | |
'nowrap', | |
'valign', | |
'vspace', | |
'width', | |
'vlink', | |
'alink', | |
'text', | |
'link', | |
'frame', | |
'frameborder', | |
'clear', | |
'scrolling', | |
'style' | |
]; | |
// Used later. | |
var attr_len = attr.length; | |
var i = list.length; | |
// Defined in loop. | |
var j; | |
var is_hidden; | |
// Loop through node list. | |
while (i--) { | |
is_hidden = list[i].style.display === 'none'; | |
// Decrement `j` in next loop. | |
j = attr_len; | |
// Loop through attribute list. | |
while (j--) { | |
list[i].removeAttribute(attr[j]); | |
} | |
/* | |
Re-hide display:none elements, | |
so they can be toggled via JS. | |
*/ | |
if (is_hidden) { | |
list[i].style.display = 'none'; | |
} | |
} | |
} |
Agreed. I just had that as a suggestion. A more limited set of DOM elements can (should) be passed in. But, not knowing the specific context of how someone might use this, just gave the widest-possible example. I'll edit the comment, to caution against possible performance woes.
Thanks for the snippet! I based a bookmarklet off this code. I found the snippet on CSS-Tricks, but now realize the original snippet is here. Just wanted to give credit!
@keithwyland — Ah, very cool. Thanks for sharing this. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems like
document.getElementsByTagName('*')
could have significant performance problems depending on how complicated the DOM is. Knowing SharePoint's penchant for deeply nested tables, you could easily be in the tens of thousands of DOM elements.