Selectors-api for data attributes

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

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

will stylize the first correctly. But attempts to select such elements using api selectors fail. Examples:

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

or

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

in Chrome and Safari, this causes a cryptic error:

SYNTAX_ERR: DOM 12 exception

Any thoughts on how to use selectors-api to correctly select elements based on data- * attributes?

+3
source share
2 answers

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

+8
source
. ( , .)
<!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>

Firefox, Opera Chrome. , div[data-foo='bar'], CSS, div[data-foo]='bar', script.

+2

Source: https://habr.com/ru/post/1741720/


All Articles