0

I have an HTML structure looks like this. Some of the element has a dynamic attribute name starts with data-ref- followed by some random hex code.

Is there away to target the attribute name partically?

[data-ref-*='group'] {
  color: red;
}
<div data-ref-15af36e1="group">foo</div>
<div data-ref-63b361af="group">bar</div>
<div data-ref-c836eea7="item">baz</div>

In this example I want the foo and bar to be red. Is it possible?

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • 1
    Unfortunately there is no way (as yet) to specify a CSS selector with a wildcard for an attribute name, see here: https://stackoverflow.com/questions/21222375/css-selector-for-attribute-names-based-on-a-wildcard – Carsten Massmann Jul 01 '21 at 01:49

1 Answers1

1

Although CSS Attribute Selectors cannot do the desired, you can use Document.evaluate() and XPATH to query the elements and set the style:

//*[@*[starts-with(name(), "data-ref-")]="group"]

var matchingElements = document.evaluate(
  '//*[@*[starts-with(name(), "data-ref-")]="group"]',
  document,
  null,
  XPathResult.ANY_TYPE,
  null
);

while (matchingElement = matchingElements.iterateNext()) {
  matchingElement.style.color = "red";
}
<div data-ref-15af36e1="group">foo</div>
<div data-ref-63b361af="group">bar</div>
<div data-ref-c836eea7="item">baz</div>
Gicck
  • 521
  • 3
  • 3