'Coloring the text of a div depending on the text value using CSS

I need to style the text in a “div” when it is populated by a Javascript function. On the initial page load, the “div’s” have no value. There will be no hard-coded value and the "div's" value of "Open" or "Closed" will change twice a day when the Javascript code runs. Here is a sample of the code I am working with.

    <! 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 tried the following additional options, none work.

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

In my particular situation, changing the color through the Javascript function is not an option. It has to be done via CSS. (Somehow)

Thanks.



Solution 1:[1]

There is no CSS selector that is capable of matching element content. Take a look at the Mozilla Web Docs - CSS Selectors.

However, you can use attribute selectors to style based on the value. Example:

h1[data-text="Hello green world!"] { color: green; }
h1[data-text="Hello red world!"] { color: red; }
<h1 data-text="Hello green world!">Hello green world!</h1>

Just make sure to have the data-text attribute identical to your actual text.

Solution 2:[2]

You're looking for a more complex stylesheet solution than css

I'd recommend sass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 fesieg