1

I'm trying to toggle a cssclass using jQuery on an SVG element each time a div element is clicked.

From what I've read, there are issues doing this with SVG elements and this way was a solution:

$("#div1").click(function() {
    $("#svg1").classList.toggle("clicked");
});`

However, this doesn't work. So I assumed it was due to the use of an SVG element in this function. But when replacing said SVG element with a div element, like this:

$("#div1").click(function() {
    $("#div2").classList.toggle("clicked");
});

the class still won't toggle, despite there being no SVG element in the function.

MeanGreen
  • 3,098
  • 5
  • 37
  • 63
Bryce
  • 45
  • 1
  • 1
  • 6
  • Any error in your console? Does your browser support [`classList`'s `toggle()` method](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility)? – Frédéric Hamidi Aug 03 '15 at 14:01
  • Reading this question and its answers may be helpful: http://stackoverflow.com/questions/8638621/jquery-svg-why-cant-i-addclass – Robert Longson Aug 03 '15 at 14:04
  • Yes, it does, I'm using Chrome, Frédéric. I got my solution from the comment posted by Tomas on that particular question, @Robert. I just found it confusing that people were claiming it to be working when it's not for me? – Bryce Aug 03 '15 at 14:14

2 Answers2

6

Please try it with plain javascript, I don't think jQuery has this method.

$("#div1").click(function() {
    document.getElementById('div2').classList.toggle("clicked");
 });

DEMO

baao
  • 71,625
  • 17
  • 143
  • 203
2

Toggle class function in jQuery is toggleClass():

$("#div1").click(function() {
    $("#div2").toggleClass("clicked");
});
Sumon Kaysar
  • 51
  • 1
  • 1
  • 5