'localStorage add/remove addClass() to data-*attribute on element based on selected radio [please see the code bellow]

I need to change addClass() to attr() that can add data-*attribute on body tag substitute for addClass().

This code can not store multiple class stores in multiple instances

I need to add data-*attr() substitute for addClass()

$box.addClass($this.data('color'));

to like :

$box.attr($this.data('color'));

that can add data-attribute on the body tag like as:

<body data-attribute-color="color-name"

Thanks for your time.

// JavaScript

$(document).ready(function() {
  let csscol = localStorage["activecol"];
  let $box = $('.box');
  //save original box classes
  $box.data('initial-classes', $box.attr('class'));

  if (csscol) {
    $box.addClass(csscol);

    // Restore checkbox as well
    $('#colors-list [type="radio"][data-color="' + csscol + '"]').attr("checked", true);
  }

  $('#colors-list [type="radio"]').on("change", function() {
    let $this = $(this);

    if ($this.is(":checked")) {
      //Replace all classes with initial classes
      $box.attr('class', $box.data('initial-classes'));
      $box.addClass($this.data('color'));

      localStorage.setItem('activecol', $this.data('color'));
    }

  });
});
/* CSS Style */

.box {
  width: 100px;
  height: 100px;
  background-color: #eee;
  margin: 50px;
  margin-top: 0;
  margin-left: 80px;
}

.color1 {
  background: #aaaaaa;
}

.color2 {
  background: #888888;
}

.color3 {
  background: #555555;
}

.color4 {
  background: #222222;
}

#colors-list {
  padding: 80px;
}
<!-- HTML Markup -->

<div id="colors-list">
  <label>
         <input type="radio" id="color1" name="colors-radio" value="1" checked="checked" data-color="color1">
         <span class="color1" title="color #1"></span>
      </label>
  <label>
         <input type="radio" id="color2" name="colors-radio" value="2" data-color="color2">
         <span class="color2" title="color #2"></span>
      </label>
  <label>
         <input type="radio" id="color3" name="colors-radio" value="3" data-color="color3">
         <span class="color3" title="color #3"></span>
      </label>
  <label>
         <input type="radio" id="color4" name="colors-radio" value="4" data-color="color4">
         <span class="color4" title="color #4"></span>  
      </label>
</div>
<div class="box"></div>

DEMO LINK



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source