I'm trying to remove all instances of a given class on the page when a button is clicked. The code works fine on its own, just not from within a click function. The code I have is:
$('#myButton').click(function() {
$("#wrapper").removeClass("myClass");
});
I'm trying to remove all instances of a given class on the page when a button is clicked. The code works fine on its own, just not from within a click function. The code I have is:
$('#myButton').click(function() {
$("#wrapper").removeClass("myClass");
});
Share
Improve this question
asked May 22, 2012 at 12:46
RyanRyan
351 silver badge5 bronze badges
7
- Are you sure the handler is even being invoked? Add the relevant HTML to your question. – tvanfosson Commented May 22, 2012 at 12:48
- This would not remove all instances of the class from a page. – asawyer Commented May 22, 2012 at 12:50
- tvanfosson - the handler is fine because if I use an alert, it is working. – Ryan Commented May 22, 2012 at 12:52
- Can you show us the relevant HTML? – jrummell Commented May 22, 2012 at 12:57
- jrummell - it's just a fixed width div with an ID of myButton, e.g. <div id="myButton" style="width:100px;">Remove Styles</div>. The click event works fine with say an alert, just not with the remove class line. – Ryan Commented May 22, 2012 at 13:00
3 Answers
Reset to default 3Just try:
$('#myButton').click(function() {
$(".myClass").removeClass("myClass");
});
which should catch every element with that class anywhere on the page.
Working demo at http://jsfiddle/alnitak/27cFm/
$("#wrapper").removeClass("myClass");
will remove myClass class only from #wrapper element (element with id "wrapper") right? May you need something like:
$('#myButton').click(function() {
$("#wrapper .myClass").removeClass("myClass");
});
First: match all the elements with myClass class inside wrapper, then remove their myClass class attribute
Please ment if I misunderstood the question thus I can fix the response
To remove all instances of myClass on the page when a button is clicked, you can try:
$('#myButton').click(function() {
// this will select all elemets with 'myClass'
var $target = $(".myClass");
// this will remove 'myClass' from the selected elements
$target.removeClass("myClass");
// this will remove the selected elements from DOM
// $target.remove();
});