Context: I have an HTML page which makes use of HTML5 data- attributes. Some of my CSS styles use attribute selectors to style elements based on the value of those custom attributes.
Problem: When I update the value of a data- attribute using JavaScript, Chrome responds correctly by restyling the affected elements but IE8 (which I am required to support) does not... not immediately. The only way to get IE8 to update the style is by directly fiddling with the CSS style in some other way (such as removing or modifying the class
attribute).
Example:
<html>
<head>
<style type="text/css">
.Test[data-foo="bar"]{ background-color: Green; }
.Test[data-foo="baz"]{ background-color: Red; }
</style>
<script src="scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
function change(div) { $(div).attr("data-foo", "baz"); }
function toggleTest() { $("DIV").toggleClass("Test"); }
</script>
</head>
<body>
<div data-foo="bar" onclick="change(this);" class="Test">Testing</div>
<div data-foo="bar" onclick="change(this);" class="Test">Testing</div>
<input type="button" onclick="toggleTest()" value="Toggle Class" />
</body>
</html>
In Chrome, you can click on the Test1 and Test2 bars and they change to red instantly. In IE8, you have to click the bar, then click the button twice (once to remove the class, again to restore it).
Question: What's the workaround? Obviously I've identified one (adding/removing the class), but it's ugly. Is there an elegant, unobtrusive way to force IE8 to reevaluate an element's style without mucking around with the element's attributes?