Home > OS >  CSS selector is not updating after click on element
CSS selector is not updating after click on element

Time:08-24

Here is my markup:

<p>This is <span >some</span> text which <span >shows</span> what I <span >want</span> to do.</p>

I have the following CSS:

span.rounded:not(.clicked):nth-child(1) {
            background: red;
        }

So, this turns the background of first rounded element to red.

Now, if i click on the word some, it applies a class clicked to the wrapping span tag. The HTML now looks like this:

<p>This is <span >some</span> text which <span >shows</span> what I <span >want</span> to do.</p>

At this point, I expect to word shows to have a red background because it seems to satisfy the selector:

span.rounded:not(.clicked):nth-child(1) {
            background: red;
        }

However, no other tag ever becomes red. What am I doing wrong?

How can I make the next tag red after the current one has been clicked?

Thanks.

CodePudding user response:

To summarise the comments, and someone please correct me if I'm wrong on this first point, but this:

span.rounded:not(.clicked):nth-child(1) {
            background: red;
        }

Doesn't work because it will always find the 1st child of the <p> parent that is a span with class rounded, and if it is not clicked, it will apply the rule.

This solution does work:

span.clicked   .rounded:not(.clicked)

This will look for a span that is clicked, find the next span with class rounded, and apply the rule only if it's not clicked.

  • Related