-1

I'm new to jQuery and I got a problem related to adding and removing classes to an element with a certain ID. This is what I want to do (and also it works just fine, but I want to know the jQuery-solution):

$('#blub').click(function() {
    document.getElementById('myelement').classList.toggle("myclass");
});

This is what I did:

$('#blub').click(function() {
    $('#myelement').toggleClass('myclass');
});

It's a fairly stupid question, probably, but I just can't find the mistake.

edit: I have added a snippet, as the syntax itself seems to be alright. Thanks your help so far :)

$('document').ready(function() {

  $('#blub').click(function() {
    $('#myelement').toggleClass('myclass');
  });
 
});
#myelement {
  fill: red;  
}

.myclass {
  fill: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="blub" style="border:none; background: none; width:300px; height:100px;">
  <svg width="100%" height="100%">
    <rect id="myelement" class="myclass" width="300" height="100" />
  </svg>
</button>
timo
  • 23
  • 5

3 Answers3

1

What you did is correct see the below example.

$('#blub').click(function() {
  $('#myelement').toggleClass('myclass');
});
#myelement {
  height: 200px;
  width: 200px;
  background-color: green;
}
#myelement.myclass {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="blub">Click</button>

<div id="myelement">
</div>
jad-panda
  • 2,509
  • 16
  • 22
0

Alternative way;

 $('#blub').click(function() {
   if($('#myelement').hasClass('myClass'))
      $('#myelement').removeClass('myclass');
   else
      $('#myelement').addClass('myclass');
 });
Serhat MERCAN
  • 1,078
  • 3
  • 14
  • 31
0

There are two issues here:

  1. One is css, the id selector overrides the styles.

    Solution:

    #myelement {
     fill: red;  
    }
    
    #myelement.myclass {
      fill: blue;
    }
    
  2. There is issue with jquery itself while dealing with svg elements jQuery SVG, why can't I addClass?

    Solution:

    $('#blub').click(function() {
      $('#myelement')[0].classList.toggle('myclass')
    });
    
Community
  • 1
  • 1
roxxypoxxy
  • 2,973
  • 1
  • 21
  • 28