3

What is the difference between the following two CSS selectors?

[attribute|=value] and [attribute^=value]

On W3Schools, the documentation says:

[lang|=en] Selects all elements with a lang attribute value starting with "en"

a[href^="https"] Selects every <a> element whose href attribute value begins with "https"

Is there a difference between "starting with" and "begins with" or will the two selectors match the same elements?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
  • 4
    Consider searching other sites besides w3schools, like MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors they have much better information. – Heretic Monkey Apr 25 '16 at 13:58
  • the two selectors are different (as they refer to different attributes) - but all other things being the same, see @MikeMcCaughan 's link... – blurfus Apr 25 '16 at 13:59

2 Answers2

12

MDN has the better description:

[attr|=value]
Represents an element with an attribute name of attr. Its value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D). It can be used for language subcode matches.

[attr^=value]
Represents an element with an attribute name of attr and whose value is prefixed by "value".

So [attr|=foo] would match attr="foo" or attr="foo-bar", but not attr="foobar".
[attr^=foo] on the other hand would match any of those.

The primary purpose of |= is, as described, for matching locale/language codes like en-us. Note that for languages specifically you should be using :lang() however, which is a lot more flexible.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

They are similar, but slightly different. As the W3 states the pipe format: [attribute|=value]

[att|=val] Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.

So that matches an element with an attribute where the value is exactly val or the value begins with val-.

[attribute^=value] matches an element where the given attribute simply begins with value. This would match <a href="https://www.google.com"> and <a href="https://www.yahoo.com">

j08691
  • 204,283
  • 31
  • 260
  • 272