Can I use contains: in a selector to select all elements with a data- attribute or is there any other way of selecting all these elements? For example all elements containing "NL" or "UK"
2 Answers
You don't want to match UKR for example if using *, so you should use ~ to find an exact match in a whitespace-separated list of words
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.
Take a look at here (2 mins read)
Attribute selectors
REF: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
[data-country~="UK"] {
color: red;
}
<span data-country="USA UK CHN">USA UK CHN</span><br>
<span data-country="USA UK">USA UK</span><br>
<span data-country="UK USA">UK USA</span><br>
<span data-country="UK">UK</span><br>
<hr>
You dont want the following to be matching:<br>
<hr>
<span data-country="USA CHN">USA CHN</span><br>
<span data-country="USAUK">USAUK</span><br>
<span data-country="UKR">UKR</span>
2 Comments
CMartins
Is it possible to do the opposite? Selecting if the data does not contains a value? I try $('[data-country*!="All"]').hide();
Dalin Huang
@CarlosMartins
span[data-country]:not([data-country~="UK"]). span[data-country] select all span with attribute data-country, :not filter all matching data-country that contain UK
[data-country*="NL"][data-country*="UK"]Attribute Contains Selector [name*=”value”]~is better, you don't want to matchUKRfor example if using*