1

I want to use :checked css pseudo-class to hide an element out of the parent of the checkbox . How i can do that ? There an exemple of my probleme:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div>
        <input type="checkbox" name="checkbox" id="checkbox">
    </div>
    <div>
        <span>Element to hide</span>
    </div>
</body>
</html>

Thanks !

1 Answers1

0

You can't use CSS alone to traverse the DOM like that. You'll need some JavaScript. CSS DOM Traversal superior than JavaScript DOM Traversal?

You could use SASS to traverse downwards, but never upwards on the stack.

document.getElementById("checkbox").onchange = (e) => {
  let checked = e.target.checked;
  if (checked) {
    document.getElementById("element-to-hide").style.display = "none";
  } else {
    document.getElementById("element-to-hide").style.display = "block";
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div>
        <input type="checkbox" name="checkbox" id="checkbox" >
    </div>
    <div>
        <span id="element-to-hide">Element to hide</span>
    </div>
</body>
</html>
ihodonald
  • 445
  • 8
  • 24
  • yes i did that but i was wondering if it was possible in css – Binary_Serox Aug 21 '20 at 17:19
  • @Binary_Serox It's not. Because you need to traverse the DOM and CSS doesn't have an implementation for DOM traversal. https://stackoverflow.com/questions/40099222/css-dom-traversal-superior-than-javascript-dom-traversal You could use SASS to traverse downwards, but never upwards on the stack. – ihodonald Aug 21 '20 at 17:21
  • 1
    okay thanks a lot ! – Binary_Serox Aug 21 '20 at 17:22
  • @Binary_Serox I updated the answer. Make sure you mark it as the correct one! :) – ihodonald Aug 21 '20 at 17:23