JSFiddle - React, Tailwind, and code Playground

by Brett

HTML

<div>
  <svg id="svg">
    <style xmlns="http://www.w3.org/2000/svg" type="text/css">
      <![CDATA[
        .red {fill: red;}
        .blue {fill: blue;}
        .lightred {fill: #ffaaaa;}
        .lightblue {fill: #aaaaff;}
      ]]>
    </style>
    <rect x="0" y="0" width="100" height="100" />
  </svg>
</div>
<div>
  <button id="redButton">Red</button>
  <button id="lightRedButton">Light Red</button>
  <button id="blueButton">Blue</button>
  <button id="lightBlueButton">Light Blue</button>
</div>

JavaScript

/*
 * .addClassSVG(className)
 * Adds the specified class(es) to each of the set of matched SVG elements.
 */
$.fn.addClassSVG = function (className) {
    $(this).attr('class', function (index, existingClassNames) {
        if (existingClassNames) {
            return existingClassNames + ' ' + className;
        } else {
            return className;
        }
    });
    return this;
};

/*
 * .removeClassSVG(className)
 * Removes the specified class to each of the set of matched SVG elements.
 */
$.fn.removeClassSVG = function (className) {
    $(this).attr('class', function (index, existingClassNames) {
        var classStr = "";
    		if(existingClassNames) {
          var classes = existingClassNames.split(' ');
          $(classes).each(function (index, item) {
              if (item !== className) {
                  classStr +=  item + " ";
              }
          });
        }
        return classStr.length > 0 ? classStr.substring(0, classStr.length - 1) : classStr;
    });
    return this;
};

var $rect = $(document.getElementById("svg")).find("rect");

function removeAll() {
	$rect.removeClassSVG("red");
	$rect.removeClassSVG("lightred");
	$rect.removeClassSVG("blue");
	$rect.removeClassSVG("lightblue");
}

function getClassStr() {
	return 'class="' + $rect.attr("class") + '"';
}

// we (should) begin with an undefined class string:
console.log(getClassStr());

$("#redButton").click(function() {
	removeAll();
  $rect.addClassSVG("red");
  console.log(getClassStr());
});

$("#blueButton").click(function() {
	removeAll();
  $rect.addClassSVG("blue");
  console.log(getClassStr());
});

$("#lightBlueButton").click(function() {
	removeAll();
  $rect.addClassSVG("lightblue");
  console.log(getClassStr());
});

$("#lightRedButton").click(function() {
	removeAll();
  $rect.addClassSVG("lightred");
  console.log(getClassStr());
});