skip to Main Content

I am trying to change the color of a span based on the title of a separate span in another div.

The following is working as expected, the second span with text2 is colored red.

span[title=Red] ~ span {
    color: red;
}
<span title="Red">text1</span>
<span >text2</span>

If the spans are in separate divs as per the below, note there are additonal attributes in case these are needed to make the selection.

Text2 is no longer colored red. What am I missing?

#form .formField span[title=Red] ~ #form .formField span {
    color:Red;
}
<div id="form">
    <div class="formField" customId="abc">
        <span title="Red">text1</span>
    </div>
    <div class="formField" customId="xyz">
         <span>text2</span>
    </div>
</div>

2

Answers


  1. To do what you want to do, you’d need to use the newer :has() pseudo-class to look down the DOM and apply the styling you want. In your second example, #form .formField span[title=Red] ~ #form .formField span, ~ won’t work because you’re trying to select #form as if it were a sibling of the span with the title, which it’s not.

    #form:has(.formField span[title=Red]) div.formField~div.formField span {
      color: red;
    }
    <div id="form">
      <div class="formField" customId="abc">
        <span title="Red">text1</span>
      </div>
      <div class="formField" customId="xyz">
        <span>text2</span>
      </div>
    </div>
    Login or Signup to reply.
  2. You can just set a normal class.

    <!-- css -->
    .red {
     color: red;
    }
    
    <!-- html -->
    <div id="form">
     <div class="formField" customId="abc">
      <span class="red" title="Red">text1</span>
     </div>
    <div class="formField" customId="xyz">
     <span>text2</span>
    </div>
    </div>
    

    https://jsfiddle.net/jasonbruce/n953ufxL/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search