Sunday, May 03, 2009
« XamlFest in SLC on May 1st | Main | Enabling PING in Windows Server 2008 and... »

As you may or may not be aware IE 7+ (and other browsers) support using CSS 2.1 attribute selectors.  Attribute selectors allow you to specify a style on an element whose element matches a particular pattern.  For instance:

td[x] { font-weight:bold; }

This selector will bold the text of any TD element on the page that has an attribute "x" (regardless of value).  Other attribute selector styles include:

...[x="value"] matches where x is exactly 'value'
...[x~="value"] matches where x contains a space-separated list of values, one of which is exactly 'value'
...[x^="value"] matches where the attribute x begins with 'value'
...[x$="value"] matches where the attribute x ends with 'value'
...[x*="value"] matches where the attribute x contains 'value'
...[x|="value"] matches where the attribute x begins with either 'value' or 'value-'

In and of themselves, these are pretty darn cool.  You can do some neat things with CSS and HTML.

I ran into an interested scenario this past week that I'd like to share.  I have some JavaScript that alters the value of attributes at runtime.  I found that the page doesn't automatically update according to the stylesheet specification.  Curiously, it would update when I moused-over the element in question.

I found, however, that I could force the issue by assigning the CSS classname to the element that it already has.  This is enough to trigger the change and have the element update according to its attribute values.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <style type="text/css">
      td[req] { font-weight:bold; }
      td[err="1"] { color:red !important; }
   </style>
   <script type="text/javascript">
      function fn() {
         var td = document.getElementById("t");
         td.err = "0";
         td.className = td.className;  // trigger the change by reassigning the CSS class
      }
   </script>
</head>
<body>
   <table>
      <tr><td class="test" err="1" req="1" id="t">Cell</td></tr>
   </table>
   <button onclick="javascript:fn();">Remove Error</button>
</body>
</html>

Interestingly, for this to work properly in a non-IE browser (such as Firefox), I found I could not use the object.property=value syntax.  Instead, I had to use the SetAttribute() function.  Also, with Firefox, reassigning the className was unnecessary.

td.setAttribute("err", "0");

That's probably the best way to handle it then, for cross-browser compliance.

CSS | Web
Sunday, May 03, 2009 9:28:44 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [1]  |  Trackback