Changing the color of a div's text based on its content with CSS

I am facing a challenge in styling the text inside a “div” element using a Javascript function. Initially, when the page loads, these “divs” contain no value. The values of the "divs" will change between "Open" and "Closed" twice a day when the Javascript code is executed. Below is an example of the code snippet I am currently working on.

    <! DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Text Color Change</title>
        
        <style>
            .txtbx {
                border: 2px solid #000;
                width: 80px;
                height: 30px;
            }
            .txtbx[value="Open"]{
                color: green;
            }
            .txtbx[value="Closed"]{
                color: red;
            }
        </style>
        <script>
            function myFunction() {
        document.getElementById("txtbx1").innerHTML = "Open";
        document.getElementById("txtbx2").innerHTML = "Closed";
            }
        </script>
    </head>
    <body>
        <div id="txtbx1" class="txtbx"></div>
        <div id="txtbx2" class="txtbx"></div>
        <button id="btn1" onclick="myFunction()">Click Me</button>
    </body>
</html>

I have experimented with different options to change the text color dynamically based on the value, but none of them seem to work as expected.

.txtbx:has(”Open”) {
Color: green;
}
.txtbx:has(”Closed”) {
Color: red;
}
.txtbx:contains(”Open”) {
Color: green;
}
.txtbx:contains(”Closed”) {
Color: red;
}

In my specific scenario, modifying the text color via Javascript is not feasible. I am required to achieve this through CSS somehow.

Thank you for your assistance.

Answer №1

Utilize the attribute method:

function switchStatus1() {
  document.getElementById("box1").setAttribute('value',"Active");
  document.getElementById("box2").setAttribute('value',"Inactive");
}
function switchStatus2() {
  document.getElementById("box2").setAttribute('value',"Active");
  document.getElementById("box1").setAttribute('value',"Inactive");
}
.status-box {
  border: 2px solid #000;
  width: 80px;
  height: 30px;
}

.status-box[value="Active"] {
  color: green;
}

.status-box[value="Inactive"] {
  color: red;
}

.status-box::before {
  content:attr(value);
}
<div id="box1" class="status-box"></div>
<div id="box2" class="status-box"></div>
<button id="btn1" onclick="switchStatus1()">Click Me</button>
<button id="btn2" onclick="switchStatus2()">Click Me</button>

Answer №2

There isn't a CSS selector that can directly target the content of an element. Refer to the Mozilla Web Docs - CSS Selectors for more information.

However, you can utilize attribute selectors to apply styles based on specific values. For instance:

p[data-info="Style me!"] { font-weight: bold; }
p[data-info="Highlight this!"] { background-color: yellow; }
<p data-info="Style me!">Style me!</p>

Ensure that the value of your attribute (e.g. data-info) matches your desired text accurately.

Answer №3

If you're seeking a more advanced approach to styling beyond basic CSS

I suggest exploring Sass

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

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

My attempt to showcase data from a database in a grid layout using PHP and HTML seems to be resulting in a vertical display instead

My code is supposed to display a grid of database information, but for some reason it keeps stacking everything vertically instead of organizing it into rows and columns like it should. I've been staring at this code all day and I just can't figu ...

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Inquire regarding the header image. Can you confirm if the current HTML and CSS for this is the most efficient approach?

This is a preview of my website in progress (Disclaimer: I'm currently learning HTML to build this site, design comes next. I know it's not the conventional way to design a site, but oh well) Check out the site here Is the HTML code for the hea ...

Unable to attach a tooltip to a list item

As an Angular developer, I am working on a list element that displays all the cars and I am looking to add a tooltip to enhance its visual appeal. Here is what I have attempted so far: I created a span tag with the class "tooltip" to wrap around the ul el ...

Utilizing Ajax and JQuery to invoke a PHP function with parameters

Seeking to implement a record deletion feature using JQuery/Ajax in order to avoid the need for page reload every time a delete action is performed. I have a Movie.php file which acts as a model object for Movie and contains a function called delete_movie ...

Instructions for outputting a string to the console in Javascript

I am looking for a versatile method to write a string to standard output in a portable manner, without automatically adding newlines at the end. I prefer it to utilize UTF-8 encoding and be compatible with: jrunscript (from any JDK) Rhino node.js Curren ...

Comparing AngularJS and AppML

As a beginner in AngularJS and AppML, I am curious to understand the strengths and differences between these two frameworks. Despite some similarities I noticed on W3Schools, I'm eager to dive deeper into each one's unique features. ...

Ways to transfer information from the Component to the parent in AngularJS 1.x

I am facing an issue with my component that consists of two tabs containing input fields. I need to retrieve the values from these input fields when the SAVE button is clicked and save them to the server. The problem lies in the fact that the SAVE function ...

What is the process of utilizing multiple npm registries within Yarn?

Currently, I am facing a challenge while setting up Yarn 0.17.9 in our environment due to issues with our registry setup. Our environment involves two registries - the official npmjs registry and our own internal network registry (Sinopia). The main issue ...

What are some strategies for reducing the data transmitted by clients over a websocket connection?

Currently, I am utilizing the ws module and I have a need to restrict the data sent by clients over websocket to 1Mb. By setting this limit, it will deter any potential malicious users from inundating the server with large amounts of data (GB scale), poten ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

Tips for displaying an alert after a successful form submission and ensuring user input validation

I created a form with PHP code to send emails, but I'm struggling to add an alert without page refresh upon submission. The alert needs to display in green or red text below the button. Validation for email input is needed, as well as protection again ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

The height of the first item in the navigation menu seems oddly disproportionate

I've been struggling for nearly an hour to make my navigation menu visually appealing. I'm utilizing Twitter Bootstrap's flat CSS menu. Oddly, the first item in the menu appears taller than all the other items in the list - you can see it h ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...

Use CSS to create a fullscreen animation for an element

Is there a way to animate a div element so that it expands to fit the screen when clicked without specifying an initial position? I need the div to be able to adjust dynamically within the screen. .box { width: 80px; height: 80px; background: red; ...

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...