What is the difference between pipe (|) and caret (^) attribute selectors?

后端 未结 4 824
广开言路
广开言路 2020-11-28 06:19

At W3Schools they declare both | and ^ to mean: Select an element with an attribute starting with a specified value.

So what\'s the differe

4条回答
  •  温柔的废话
    2020-11-28 07:01

    Simply put:

    E[foo|="en"] matches...

    an E element whose "foo" attribute has a hyphen-separated list of values beginning with "en"

    E[foo^="bar"] matches...

    an E element whose "foo" attribute value begins exactly with the string "bar"

    Expanded Info:

    [att|=val]

    Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-". This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML).

    [att^=val]

    Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

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


    Examples

    HTML

    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors

    Testing the pipe (|) selector.

    li[title|="testing"] { background-color: aqua; }
    

    Testing the caret (^) selector.

    li[title^="testing"] { background-color: pink; }
    

    #pipe > li[title|="testing"] {
      background-color: aqua;
    }
    #caret > li[title^="testing"] {
      background-color: pink;
    }

    Testing the pipe (|) selector.

    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors

    Testing the caret (^) selector.

    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors
    • testing attribute selectors

    jsFiddle

提交回复
热议问题