The CSS attribute selector allows you to select HTML elements based on their attributes. For example, take the following markup:
1 2 3 4 5
In a compliant browser, here are some selectors you can use to target these list items.
1 2 3 4 5 6 7 8
This is all well and good in most all modern browsers. Unfortunately IE7 is buggy when handling this selector. For those of use that are still unlucky enough to be supporting it, I thought it would be nice to have some of these documented.
DOM Attributes == HTML Attributes?
1 2 3 4 5 6 7 8 9
In IE8+ (and everywhere else for that matter) the following attribute selector will select the label:
In IE7 this won’t work. You’ll need to use the incorrect
So if you’re still supporting IE7 you’ll almost certainly want to include them together:
Along the same lines, IE7 will incorrectly select attributes based on the className attribute:
Fortunately IE7 also supports selecting using
IE8 fixed both of these bugs and selecting for the attributes
className no longer work.
It’s impossible to target empty attributes via CSS in IE7. As an example, let’s say you apply a custom HTML5 data attribute to nodes at random throughout the DOM. Let’s say you want to select only the ones that have an empty value, for example the h3 below:
1 2 3
You would write this selector and call it a day:
querySelectorAll isn’t supported until IE8, so you need a selector engine to target these nodes. Here’s how you can do it in jQuery:
If you’re using Dojo yet another step is necessary. For whatever reason running…
…returns not only the nodes with empty attributes, but also all the nodes that don’t have the attribute declared at all! Furthermore,
dojo.query('[data-state]') incorrectly doesn’t return nodes that have the attribute with an empty value. So you need the following approach to select the nodes in IE7.
1 2 3 4 5 6
Descendant Selector Typos
Let’s say you have the following markup.
1 2 3
…and you want to apply some styling to the paragraph, maybe something like this:
1 2 3
Notice how there’s no space between the “]” and the “p”, that’s a syntax error, right? Correct… except in IE7! IE7 will incorrectly parse this as if a space were there and change the color of the paragraph to red.
This was also fixed in IE8.
We’re actually really fortunate that the attribute selector is supported in IE7. It’s a very useful tool to have available and it can help solve a lot of real world issues. And if you’ve dropped IE6 support they’re finally safe to use.
While support is buggy, the attribute selector does work for the vast majority of use cases. However, knowing to look out for these bugs can save hours of frustration. Yet another reason for IE7 to fall off the face of the Earth. Happy hacking.