ラジオボタンを2回クリックで選択解除する

jQuery使用無しで、ラジオボタンの項目を2回(すでに選択されている項目)をクリックすることで選択状態をリセットする方法。

/**
 * 指定classのラジオボタンを2回押しで解除する
 * 'checked' classの付け替えで状態管理
 */
document.querySelectorAll('.js-clearableRadio').forEach(box => {
  const radioButtons = box.querySelectorAll('input[type="radio"]');

  radioButtons.forEach(radioButton => {
    radioButton.addEventListener('click', () => {
      // event.preventDefault();

      if(radioButton.classList.contains('checked')) {
        radioButton.checked = false;
        radioButton.classList.remove('checked');
      }
      else if(radioButton.checked) {
        radioButton.classList.add('checked');
      }

      radioButtons.forEach(afterChangedButton => {
        // チェック項目変更後のfalseになった項目から 'checked' classを削除
        if(afterChangedButton.checked === false) {
          afterChangedButton.classList.remove('checked');
        }
      })
    })
  })
});

以下のようにhtmlを記述して使用します。

<div class="js-clearableRadio">
  <input type="radio" name="name" id="radio01">
  <input type="radio" name="name" id="radio02">
</div>