Skip to content

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

(updated)

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

See more stuff that I've learned

comments

Leave a reply

Required fields denoted by *

Your comment will be revised by the site if needed.