views:

78

answers:

2

In HTML5, CSS selectors seem to operate well with data-* attributes. For example:

<style>
div[data-foo='bar'] {
  background:#eee;
}
</style>
<div data-foo='bar'>colored</div>
<div>not colored</div>

will properly style the first . But, attempts to select such elements using the selectors-api fail. Examples:

var foos = document.querySelectorAll("div[data-foo]='bar'");

or

var foos = document.querySelectorAll("div data-foo='bar'");

in Chrome and Safari, this produces a cryptic error:

SYNTAX_ERR: DOM Exception 12

Any thoughts on how to use the selectors-api to properly select elements on the basis of data-* attributes?

+4  A: 

The syntax for attribute selectors is [att=val] so you want "div[data-foo='bar']".

Anne
Right -- the first one. But, that still give an error message in Chrome. Does it work in any browsers for you?
dTRN
A: 

Anne is right. (Fortunately, as he is one of the editors of the relevant specification.)

<!DOCTYPE html>
<style>
div[data-foo='bar'] {
  background:blue;
}
</style>
<div data-foo='bar'>colored</div>
<div>not colored</div>
<script>
var foos = document.querySelectorAll("div[data-foo='bar']");
alert(foos[0])
</script>

works for me is Firefox, Opera and Chrome. Note that it's div[data-foo='bar'], as you used in the CSS, rather than div[data-foo]='bar', as you used in the script.

Ms2ger
Got it -- thanks!
dTRN