Target an attribute’s value with a specified string in CSS

The other day I had a situation where I needed to hide some form fields a WooCommerce plugin was adding to a product. Unfortunately there wasn’t a way to remove them in the plugin settings, so I needed to hide them with CSS. The only way to target the specific fields was using the element’s ID.

The IDs ended up being unique, looking something like:

<p id="message[1546]" class="form-row">…</p>

Where the numeric value was a unique ID related to the product.

That’s when I learned about CSS attribute selectors.

I was able to do something like:

p[id^=message] {
    display: none;
}

to target the message field specifically.

The MDN docs explain everything in more detail, but in short:

  • attribute^=value matches the specified attribute whose value is prefixed with the specified value.
  • attribute$=value matches the specified attribute whose value is suffixed with the specified value.
  • attribute*=value matches the specified attribute whose value contains the specified value at least once.

References


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *