3

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
  • 2
    [data-country*="NL"][data-country*="UK"] Attribute Contains Selector [name*=”value”] Commented Sep 13, 2017 at 6:26
  • 1
    @Satpal in this case use ~ is better, you don't want to match UKR for example if using * Commented Sep 13, 2017 at 6:40

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to do the opposite? Selecting if the data does not contains a value? I try $('[data-country*!="All"]').hide();
@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
1

You can use like this too:

$('[data-country^="UK"]') {
  color: red;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.