Target an Attribute's Value with a Specified String in CSS

Topic: CSS

Published on Updated

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:

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

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.