We have a CMS that likes to insert inline styles, I have written some code that removes the inline styles adds a class and rewrites the contents of the style attribute into a style tag in the head.
Example HTML
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="container">
<p style="width: 50%;">Blah blah blah</p>
<p style="font-weight: bold;">Even more blah blah blah</p>
<p>Can I get some blah blah blah</p>
<p>Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
jQuery function
$.each($('#container [style]'), function(index, el){
var cssText = el.style.cssText;
var className = "auto-class-" + index;
$(el).removeAttr("style");
$(el).addClass(className);
$("<style type='text/css'> ." + className + "{" + cssText + "} </style>").appendTo("head");
})
Desired Result HTML
<html>
<head>
<title>Title</title>
<style type="text/css"> .auto-class-1 { width: 50%; } </style>
<style type="text/css"> .auto-class-2 { font-weight: bold; } </style>
</head>
<body>
<div id="container">
<p class="auto-class-1">Blah blah blah</p>
<p class="auto-class-2">Even more blah blah blah</p>
<p>Can I get some blah blah blah</p>
<p>Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
I all the good browsers this works as expected, but in IE6 the jQuery [style] selector seems to grab all the elements inside the #container. So you get the following instead.
Result HTML in IE6
<html>
<head>
<title>Title</title>
<style type="text/css"> .auto-class-1 { width: 50%; } </style>
<style type="text/css"> .auto-class-2 { font-weight: bold; } </style>
<style type="text/css"> .auto-class-3 { } </style>
<style type="text/css"> .auto-class-4 { } </style>
</head>
<body>
<div id="container">
<p class="auto-class-1">Blah blah blah</p>
<p class="auto-class-2">Even more blah blah blah</p>
<p class="auto-class-3">Can I get some blah blah blah</p>
<p class="auto-class-4">Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
In the example above this doesn’t cause any issues but on our website where there are over 300 DOM nodes on any given page it’s a mess.
The question is how can I select only the DOM nodes with a style attribute in IE6.
Also is there an easy way to write all the rules into one style tag rather than having a separate style tag for each rule.
This isn’t an answer to the specific question you asked, but it is what I think you should do.
You said in a comment:
The solution you’re using (moving inline styles to
<style>elements) is not very elegant.You’d be much better off adding
!importantto every single declaration in your print stylesheet.Yes, this is ugly, but it’s much cleaner than a JavaScript-based solution.
If you’d like some background information:
See: http://css-tricks.com/specifics-on-css-specificity/