How to get CSS to select ID that begins with a string (not in Javascript)?

前端 未结 4 474
心在旅途
心在旅途 2020-12-07 08:55

If the HTML has elements like this:

id=\"product42\"
id=\"product43\"
...

How do I match all of those id\'s starting with \"product\"?

相关标签:
4条回答
  • 2020-12-07 09:02

    I noticed that there is another CSS selector that does the same thing . The syntax is as follows :

    [id|="name_id"]
    

    This will select all elements ID which begins with the word enclosed in double quotes.

    0 讨论(0)
  • 2020-12-07 09:12

    Use the attribute selector

    [id^=product]{property:value}
    
    0 讨论(0)
  • 2020-12-07 09:15

    I'd do it like this:

    [id^="product"] {
      ...
    }
    

    Ideally, use a class. This is what classes are for:

    <div id="product176" class="product"></div>
    <div id="product177" class="product"></div>
    <div id="product178" class="product"></div>
    

    And now the selector becomes:

    .product {
      ...
    }
    
    0 讨论(0)
  • 2020-12-07 09:21
    [id^=product]
    

    ^= indicates "starts with". Conversely, $= indicates "ends with".

    The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

    See the specs for full information.

    0 讨论(0)
提交回复
热议问题