Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all classes from SVG using jquery

here is my code

<!DOCTYPE html>
<html>
<body>
<style>    
   .someClass {
            fill:gray;
        }
</style>
<svg width="400" height="110">
  <rect class="someClass" width="100" height="100"/>
</svg>
 <svg width="400" height="110">
  <rect class="someClass" width="100" height="100"/>
</svg>
 <svg width="400" height="110">
  <rect class="a" width="100" height="100"/>
</svg>
</body>
</html>

How to remove all classes(.someClass) need to remove only in .someClass in document without using id?

like image 616
Akbar Basha Avatar asked Apr 20 '15 12:04

Akbar Basha


People also ask

How do I delete a class in SVG?

In order to remove SVG content, you can use the remove() function provided by D3. js.

How to remove svg element in jQuery?

parentElement could be for example $('g:first', svgRoot), where svgRoot refers to the embedded SVG element. rect. parentNode. removeChild(rect);

How to remove classes in jQuery?

jQuery removeClass() Method The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.

How to remove div class in jQuery?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.


2 Answers

You can't call .removeClass() on a SVG, unfortunately.

Use .attr() instead.

$('.someClass').attr('class','');

additional sources:

Martin Wolf

Similar SO Question

like image 89
Josh Stevenson Avatar answered Oct 19 '22 17:10

Josh Stevenson


This ( $('.someClass').attr('class',''); ) will delete all the classes of all elements with class someClass.


This should do the trick ( retains other classes):

$(".someClass").each(function(){

     var classes = $(this).attr("class").split(" ");
     var otherClasses = "";
     for(var i = 0; i<classes.length; ++i){
        if(classes[i] !== "someClass"){
            otherClasses += classes[i] + " ";
        }
     }

     $(this).attr("class",otherClasses);

});

Thanks @xehpuk for his comments.

like image 7
dsharew Avatar answered Oct 19 '22 17:10

dsharew