2

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
  • if item is on all then can add item red.. then class selector would be .item.red, without a space between.. then it has to have at least class="item red".. is just basic css Commented Oct 21, 2020 at 21:45
  • [attribute^='value'] and [attribute$='value'] just selects HTML tags that begin with the attribute value and ends with the attribute value, respectively. That does not mean that it will see if a class attribute value within your attribute begins with or ends with the value. Just use div.prefix-item-suffix{} and create other classes to do other things. Commented Oct 21, 2020 at 21:57

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

*= just means contains, and does not account for order.
You'll need to add the appropriate hyphen after the prefix match and before the suffix match. Otherwise, you'll match all classes having the string in any part of the class. For example, [class*="prefix-"].
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.