CSS Target Attribute Containing Partial Match
Asked Answered
M

2

5

Using the following CSS, why am I not able to target the 3 following anchor tags?

a[href~="checkout"] { /* Do something. */ }

<a href="http://shop.mydomain.com/checkout/onepage/">
<a href="https://shop.mydomain.com/checkout/onepage/">
<a href="https://shop.mydomain.com/checkout/onepage/?___SID=S">

What am I doing wrong in my CSS selector? I'm trying to select a partial match using ~= for all URLs containing the word "checkout."

Marcelo answered 27/5, 2015 at 5:25 Comment(0)
W
16

Try this

a[href*="checkout"] { /* Do something. */ }

You have to use *, which means contain - see reference.

Also, don't forget to close anchor tags

</a>

Working JSFiddle

Waldowaldon answered 27/5, 2015 at 5:30 Comment(2)
Then what is ~= used for?Marcelo
You use ~= if containing a specific word. I.e. a[class~="checkout"] when <a class="link green checkout"></a>Waldowaldon
P
4
a[href~="checkout"]

matches elements where in a whitespace-separated list of words one of these is exactly "checkout".

See W3C Docs for Selectors Level 3:

[att~=val]

Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.

Source: http://www.w3.org/TR/css3-selectors/#attribute-selectors

If you want to match all elements where attr contains string, use

[attr*=string]
Pooler answered 27/5, 2015 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.