How to target a part of CSS class name?

Viewed 972

Example 1 works:

HTML:

<div class="items">
  <div class="item">item 1</div>
  <div class="prefix-item-suffix">item 2</div>
  <div class="item">item 3</div>
</div>

CSS:

div[class^="prefix"][class$="suffix"] {
  color: red;
}

Example 2 doesn't:

HTML:

<div class="items">
  <div class="item">item 1</div>
  <div class="multiple prefix-item-suffix classes">item 2</div>
  <div class="item">item 3</div>
</div>

CSS:

div[class^="prefix"][class$="suffix"] {
  color: red;
}

Example 2 has multiple classes so CSS approach stops working. In real time project the multiple classes will be random except the one targeted in between them, the value between prefix-the_dynamic_value-suffix will also be random, how to target that with other classes inside same element? Because example 1 approach doesn't work.

2 Answers

Try [class*=…]

div[class*="prefix-"][class*="-suffix"] {
  color: red;
}
<div class="items">
  <div class="item">item 1</div>
  <div class="multiple prefix-item-suffix classes">item 2</div>
  <div class="item">item 3</div>
</div>

You could do this with js by checking if some class on the element starts with prefix and ends with suffix. If the check returns true then you run your code.

document.querySelectorAll('.items > div').forEach(el => {
  const check = [...el.classList].some(cls => {
    return cls.startsWith('prefix') && cls.endsWith('suffix')
  })

  if (check) {
    el.style.color = 'red'
  }
})
<div class="items">
  <div class="item">item 1</div>
  <div class="multiple prefix-item-suffix classes">item 2</div>
  <div class="item prefix-item-suffix-not-this">item 3</div>
</div>

Related