Manipulating CSS classes on SVG elements

von

SVG is a nice for modern web pages. However, browser or framework support is sometimes… well, not that convincing.

Consider the following code:

<a href="#" data-group="1">
  <svg class="nav-button active">
  ...
  </svg>
</a>
<a href="#" data-group="2">
  <svg class="nav-button">
  ...    
  </svg>
</a>

Now you would like to programmatically “move” the .active class from one SVG to the other. One can do this easily with removing the active class from all elements first, and then add it to the new selection.

How to change css classes

It should be easy. In MinifiedJS it should look like that:

var navButtons = $('.nav-button');
navButtons.set('$', '-active');
navButtons[1].set('$', '+active');

jQuery 2 behaves similar:

$(navButtons[1]).addClass("active");

But this won’t work on SVG as your JS framework needs to support it. Support for this is coming with jQuery 3 and hopefully for MinifiedJS too.

There is a workaround: just manipulate the actual attribute.

With MinifiedJS it would look like this:

navButtons.set('@class', 'nav-button');
$(navButtons[1]).set('@class', 'nav-button active');

With jQuery, it would be:

navButtons.attr("class", "nav-button");
$(navButtons[1]).attr("class", "nav-button active");

Image credits

Tags: #JavaScript #jQuery #MinifiedJS #SVG

Newsletter

ABMELDEN