skip to Main Content

Hello everyone I’m a beginner trying to get better at css. How can you target an element from another div in events like hover, checked, etc.

see example of what I mean below:

<div>
<input type="checkbox">
</div>


<div>

<button>example</button>

</div>

input:checked /how do I target button/{
background-color:#f0f0f0;
}

I learned that I can target sibling with ~ example
/if they were siblings/

input:checked ~ button {
background-color:#fefefe;
}

how can I do similar on elements from different parents.

2

Answers


  1. To my knowledge this is only possible with a little JavaScript. Here is one way of doing it:

    document.querySelectorAll("[type=checkbox]").forEach(cb=>cb.onchange=ev=>
    ev.target.closest("div").nextElementSibling.querySelector("button").style.backgroundColor=ev.target.checked?"red":"")
    div {background-color:#ddd; margin:6px}
    <div>first div <input type="checkbox"></div>
    <div>second div text <button>example</button></div>
    <div>third div <input type="checkbox"></div>
    <div>fourth div text <button>example</button></div>

    The onchange event handler is defined for each checkbox in the document. Whenever its status changes the event handler will start traversing the DOM structure up to the closest parent that is a div. It will then try to find the immediately following "ElementSibling" and select the first "button" element in it. For this element the background colour is then changed, according to the status of the changed checkbox.

    The script is still in a "quick and dirty" stage and does not yet provide suitable responses in case the querySelector() should not come up with a DOM element as a result.

    Login or Signup to reply.
  2. While it is possible to achieve this using JavaScript or obscure CSS tricks, it’s important to note that relying on relative position can be risky as it is unstable. Instead, consider adding an identifier to the button and changing its status/style in the input tag’s event handler.

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