Setting the style attribute

Benchmark created by David Mark on


Like most browser scripting operations, setting an element’s STYLE attribute may or may not be needed (most apps not). Of course, most libraries attempt to clear that hurdle in one way or another. You get the extra code (and overhead) whether it is beneficial or not. A lot of libraries (as well as old copies of others) use UA-based browser sniffing to “fix” issues with IE5/6/7/compat mode.

Preparation HTML

<script src="//"></script>
 * Context here is an HTML5 document
 * Appropriate build for this context would exclude XHTML support
 * Next line asserts document will create an HTML DOM
 * There are virtually no documents on the Web that create an XHTML DOM
var API = { disableXmlParseMode:true };
<script src="//"></script>
  // For all tests
  var elHtml = document.documentElement;
  var css = 'color:black;background-color:white';
  // For My Library test
  var setAttribute = API.setAttribute;
  // For cross-browser test
  // Remove else case to degrade in IE under 8
  // First branch weeds out bad IE browsers (and other older browsers)
  // For completeness, should probably do a try-catch on a set as well
  // Can check that styles take in properties and (in some cases) in layout
  if (elHtml) { // Need this for detection, could also create element
    if (elHtml.setAttribute && elHtml.getAttribute && typeof elHtml.getAttribute('style') == 'string') {
      var setStyleAttribute = function(el, css) {
        el.setAttribute('style', css);
    } else if ( && typeof == 'string') {
      var setStyleAttribute = function(el, css) { = css;

Test runner

Ready to run.

Testing in
My Library
setAttribute(elHtml, 'style', css);
jQuery(elHtml).attr('style', css);
// NOTE: Would not normally have API feature detection in loop

if (setStyleAttribute) {
  setStyleAttribute(elHtml, css);
} else {
  throw new Error('Abort due to degraded browser');


You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by David Mark on