Adjacent sibling selector

by Joseph Sebast

HTML

<main>
  <h1>
    CSS adjacent siblings selector
  </h1>

  <form>
    <fieldset>
      <legend>Select one:</legend>

      <div class="options">
        <label>
          <input type="radio" name="contact" value="1" /> 
          Option 1
        </label>

        <label>
          <input type="radio" name="contact" value="2" />
          Option 2
        </label>

        <label class="checked">
          <input type="radio" name="contact" value="3" checked />
          Option 3
        </label>

        <label>
          <input type="radio" name="contact" value="4" />
          Option 4
        </label>

        <label>
          <input type="radio" name="contact" value="5" />
          Option 5
        </label>

        <label>
          <input type="radio" name="contact" value="6" />
          Option 6
        </label>
      </div>

      <button type="submit">Submit</button>
    </fieldset>
  </form>  
</main>

CSS

/* highlight selected element */
label.checked {
  background: blue;
  color: yellow;
}

/* highlight it's previous sibling */
label.checked + label {
  background: yellow;
  color: blue;
}

/* highlight it's next sibling */
label:has(+ label.checked) {
  background: yellow;
  color: blue;
}

/* unimportant */
.options {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
/* unimportant */

JavaScript

const setSelected = (e) => {
	const checkedClassName = "checked";
	const checkedLabel = document.getElementsByClassName(checkedClassName)[0];
  checkedLabel.classList.remove(checkedClassName);
  e.currentTarget.classList.add(checkedClassName);
}

const labels = document.getElementsByTagName("label");
for (const label of labels) {
	label.addEventListener("click", setSelected);
}