public
Last active

Remove inline styles

  • Download Gist
remove_style.js
JavaScript
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
//
// 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(all) {
var i = all.length;
var j, is_hidden;
 
// 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'
];
 
var attr_len = attr.length;
 
while (i--) {
is_hidden = (all[i].style.display === 'none');
 
j = attr_len;
 
while (j--) {
all[i].removeAttribute(attr[j]);
}
 
// Re-hide display:none elements,
// so they can be toggled via JS.
if (is_hidden) {
all[i].style.display = 'none';
is_hidden = false;
}
}
}

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.

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!

http://keithwyland.github.com/attrebuke/

@keithwyland — Ah, very cool. Thanks for sharing this. :)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.