0

I have the following code:

<input id="checkboxWithGeneralSiblingSelector" type="checkbox"/>
<span id="span1">Text</span>
<br/><br/>
<input id="checkboxWithoutGeneralSiblingSelector" type="checkbox"/>
<span id="span2">Text2</span>

And CSS:

#checkboxWithGeneralSiblingSelector:checked ~ #span1 {
    font-weight: bold;
}

#checkboxWithoutGeneralSiblingSelector:checked #span2 {
   font-weight: bold;
}

The first one works fine, it looks at its general siblings and gets the element with ID span, so I assumed the second one would look at the entire DOM and give me the element with id span2. But then I realized that no operator is actually the "descendants" operator aka it looks for a span2 element inside the initially selected one.

JSFiddle

This fiddle is oversimplified, in my case the span is in no relation with the checkbox, aka it cannot be selected with either +, > or ~

EDIT: Simplified example of my DOM:

<span id="toBeAffected">
...
<div>
    <div>
        <input id="trigger" type="checkbox"/>
    </div>
</div>

How can I affect an item with no specific DOM relation to the current one, when the effect needs to be conditioned by a state of the initially selected item?

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
iuliu.net
  • 5,195
  • 3
  • 36
  • 63
  • Does this have to be achieved via CSS only, or can/would you use a JS solution also? – Aember Apr 26 '16 at 10:46
  • @dippas Added example of my DOM. – iuliu.net Apr 26 '16 at 10:48
  • @Aember I can, definitely. But I really feel like this should be doable via CSS – iuliu.net Apr 26 '16 at 10:49
  • @iuliu.net you can't affect parent in CSS, because there is no parent selector in CSS – dippas Apr 26 '16 at 10:50
  • You cannot affect any element that preceeds the trigger element in the DOM. Affecting subsequent elements is possible depend on the structure. This is why Javascript exists – Paulie_D Apr 26 '16 at 10:52
  • So basically, the only things you can select are the ones on the same level or lower than the selected element? – iuliu.net Apr 26 '16 at 10:54
  • Essentially...yes. – Paulie_D Apr 26 '16 at 10:54
  • Oh.. ok. This feels like a really needed feature to me tho. Thanks anyway. – iuliu.net Apr 26 '16 at 10:55
  • It's not a question of whether you can affect an element with no structural relation to the current one, but whether you can express this relation in a selector. In theory, with :has(), a structural relationship can be expressed between *any two elements* using a selector. – BoltClock Apr 26 '16 at 11:10

1 Answers1

0

You can wait for :has pseudoclass, and then do something like in this fiddle (Today, April 2016, it doesn't work in any browser)

.sibiling:has(input:checked)  ~  #toBeAffected {
    font-weight: bold;
}

Here is an helpful link:

https://stackoverflow.com/a/1014958/2594354

Community
  • 1
  • 1
PaoloCargnin
  • 420
  • 2
  • 10