0

I want to remove class in html code. So I use the removeClass function in Jquery. However, it doesn't work. To be more specific in the code, I want to let the opacity of graph become 0(disappear) when I click remove button. However it does nothing. I don't know what's wrong there. Can anyone explain a little bit? Thanks in advance!

Here is Jsfiddle Link Here is real code:

<!DOCTYPE html>
<html>
<head>

   <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
   <script type="text/javascript">

  function remove_R() {
      $(".me rect").removeClass("rect_obvious");
  }

  </script>
  <style type="text/css">
  .rect_style {
     stroke:black;
     stroke-width:5;

  }
  .rect_color_1{
      fill:#FFC863;
  }

  .rect_obvious{
        opacity:1;
  }  

  .rect_none{
    opacity: 0;
  }
  </style>
</head>


<body>

<svg class="me" width="145" height="65"><rect  class="rect_style rect_color_1 rect_obvious" x="3" y="3" rx="20" ry="20"  width="140" height="60" ></svg>
<button onclick="remove_R()">remove</button>

</body>
</html>
user3920796
  • 35
  • 1
  • 6

3 Answers3

1

element rect has class rect_obvious and not .me.so use:

 $(".me rect").removeClass("rect_obvious");
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • I added it into the code. http://jsfiddle.net/qn079oqa/1/ . However it still doesn't work. – user3920796 Aug 21 '14 at 15:56
  • The remove_R function is not executed in your fiddle. remove_R is not defined as says Chrome's Javascript console. – tomaoq Aug 21 '14 at 15:58
  • @lechariotdor Thanks for your response. So what should I do if I want remove_R to be executed? – user3920796 Aug 21 '14 at 16:02
  • @lechariotdor Hi, now I put javascript code into the html and used an alert message to show that the remove_R function have been executed. This link is http://jsfiddle.net/qn079oqa/3/. removeClass still doesn't work. – user3920796 Aug 21 '14 at 16:10
1

It works when I change code:

$(".me rect").removeClass("rect_obvious");

into:

$(".me rect").attr("class", "rect_obvious rect_none");

Note: The Jsfiddle link

removeClass, addClass and toggleClass are not fit for SVG.

This question is similar to the one: jQuery SVG, why can't I addClass?

Thanks,Jay Blanchard. He reminded me about this!

Community
  • 1
  • 1
user3920796
  • 35
  • 1
  • 6
0

Besides the problem of accessing the wrong node $('.me'), the other problem is that your using a svg tag which is "special", jQuery returns false for the hasClass.

A work around it to pull the class attribute, modify it and then setting it to the new value.

http://jsfiddle.net/qn079oqa/4/

Bogus Hawtsauce
  • 363
  • 3
  • 10