What is the best way to focus on a specific section of a CSS class name?

Successfully Working Example:

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;
}

Non-Functioning Example:

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;
}

The second example contains multiple classes, causing the CSS method to fail. In a real project scenario, these additional classes will be random, except for the targeted one in the middle - prefix-the_dynamic_value-suffix. Is there a way to target this specific class combination while ignoring the other random classes present in the element? The approach used in example 1 is not effective for this case.

Answer №1

For a solution, consider using the selector [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>

Answer №2

To achieve this using JavaScript, you can check if a certain class on the element starts with prefix and ends with suffix. If the condition is met, then you can execute 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with clearing divs function not working as expected

I'm facing a challenge in properly aligning 3 div elements without resorting to adding padding at the bottom of the wrapping div, which isn't the most practical solution. Check out the issue demo here How would you suggest addressing this parti ...

React-Redux showing no errors despite non-functional Redux store

I'm currently facing an issue with integrating React-Redux into my React Native/Expo project. Despite not receiving any console error messages, the data from the Redux store is not displaying in the user interface. Below are some key files related to ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Issues with unresponsive links (HTML5/CSS)

As a beginner, I've encountered an issue where my previously working links are no longer functioning. Can anyone help identify what could be going wrong? Below is the HTML code: <!doctype html> <html> <head> <meta charset="UTF-8 ...

Achieving dynamic key assignment when updating with mongoose in NodeJS and Express

With a multitude of keys requiring updates from a single function, I am seeking guidance on how to dynamically set the key for updating. static async updateProfile(req, res, next) { const userId = req.body.userId; // The key requiring an update ...

Unable to pass several parameters to a Component

I'm attempting to send three URL parameters to a React Component. This is my approach: App.js: <Route path="/details/:id(/:query)(/:type)" handler={DishDetails}/> DishDetails.js: class DishDetails extends Component { constructor(props) { ...

Is there a way to retrieve a file received in a response to a POST request using nodejs?

I'm encountering an issue with sending a POST command to download a file. I am attempting to send a POST request with a specific URL from the client side, along with a parameter that indicates the file to be downloaded. var req = $.ajax({ type: ...

Picture not adapting correctly to various screen sizes

I'm looking to adjust the size of an image based on the user's browser window. Here is the code I have so far: .image { max-height: 15%; width: auto; } The image class is used in this section of my code: <ul> <li> <img c ...

What is the method for generating an oval shape with a border-radius in CSS?

Is there a way to create an oval shape instead of a rectangle with rounded edges using CSS? Below is the code snippet I have been working with: div { position: fixed; border-radius: 25px; background: rgba(0,0,0,.5) width: 100px; height: 50px; ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

Looking for assistance in retrieving a document by its reference id from Firestore using ReactJS?

As a newcomer to using firestore and reactjs, I am currently working on creating a basic react code that retrieves documents from 2 different collections. The two collections I am focusing on are: user-habits {email, habitid} habits {habitid, conte ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Issue with ERR_HTTP_HEADERS_SENT persists despite implementation of return statements

When attempting to send a POST request to the server, an error is encountered: Error [ERR_HTTP_HEADERS_SENT]: Cannot modify headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_h ...

transmitting comfort through events

To enhance my application, I am working on publishing a solace message to a topic and then passing it along to another part of the app for further processing using events. This entire process is happening within a single node.js process. While I understand ...

Perform two iterations, hover over a button, and update the related element

I have a situation where I need to make two loops work together. One loop contains buttons, while the other loop contains spans. The goal is that when I hover over a button, the corresponding span should change color. Both elements have a count that should ...

ReactJS Navbar component experiencing CSS hover bug

While developing a navbar component in React, I encountered an unexpected issue - the hover effect on my navigation links suddenly stopped working. Strangely enough, the cursor: pointer functionality still operates on my logo but not on the nav links durin ...

Seeking assistance with my personal portfolio project - any takers?

I'm facing an error on a coding challenge that says: "The height of the welcome section should be equal to the height of the viewport." I have set it to 100vh but I'm unsure how to resolve it. Here is the HTML code: <header> <nav id=& ...

What is the best way to showcase the final div at the top with CSS?

I'm working with 4 separate divs, with the last one acting as a footer. Is there a way to position this last div at the top using CSS? ...