Selecting Elements with a Partial Attribute Name

CSS selectors (and document.querySelector()) let you select elements by matching the names and values of their attributes. It’s possible to match part of an attribute’s value using [attribute*=], [attribute^=], [attribute$=], but there’s no way to select an element based on matching only part of an attribute name.

Thankfully this is something we can do via XPath in all modern browsers (excluding IE11) like this:

document.evaluate(
  '//*[@*[starts-with(name(), "data-custom-")]]',
  document, 
  null, 
  XPathResult.UNORDERED_NODE_ITERATOR_TYPE, 
  null
)

This XPath selector, //*[@*[starts-with(name(), "data-custom-")]], returns all nodes with an attribute name that starts with data-custom-, so it would match elements with data-custom-name and data-custom-example, but not data-customizer.

For those wishing to select elements with this ability while authoring CSS, here are a few workarounds that can help:

Parts Required

JS Tests

To find an attribute that begins with attribute-name-:

/^.*attribute-name-/.test(element.outerHTML)

Plugins Capable

Syntax Examples

EQCSS

@element * {
  eval("/^.*data-item-/.test(outerHTML) && '$this'") {
    background: lime;
  }
}

Selectory

[test="/^.*data-item-/.test(this.outerHTML)"] {
  background: lime;
}

XPathy

[xpath="//*[@*[starts-with(name(), 'data-item-')]]"] {
  background: lime;
}

Demos