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>
There are two issues here:
One is css, the id selector overrides the styles.
Solution:
#myelement {
fill: red;
}
#myelement.myclass {
fill: blue;
}
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')
});