Attempt to removeClass in jquery fails

223 Views Asked by At

I am attempting to remove the classes div1 and intro from this HTML code.

Snippet sample :

$(function() {
  $('div').on('click', function() {
    alert("Hello");
    $("div").removeClass("div1");
    $("p").removeClass("intro");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">div 1</div>
<div class="div2">div 2</div>
<div class="div3">div 3</div>
<div class="div4">div 4</div>
<p class="intro">This is a paragraph.</p>
<p class="intro">This is another paragraph.</p>

Now when I click on the div I get hello alert but div1 and intro classes are not removed. Any suggestions on what I might be missing here ?

Update: I should have been using remove instead of removeClass. Fiddle sample.

3

There are 3 best solutions below

6
Hodrobond On BEST ANSWER

It appears the issue was a misunderstanding between remove and removeClass. OP wanted to remove an element from the DOM, and should therefore use remove(), instead of wanting to remove the class using removeClass()

jsfiddle

1
Yaser On

You're selecting p element and trying to remove div1 and div2 classes that are on div's:

$(function() {
  $('div').on('click', function() {
    
    $("div").removeClass(function (index, className) {
      return (className.match (/div[0-9]/g) || []).join(' ');
    });
    $("p").removeClass("intro");
  });
});
.div1, .div2, .div3, .div4 {
    border: 1px solid red;
  }

.intro {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">div 1</div>
<div class="div2">div 2</div>
<div class="div3">div 3</div>
<div class="div4">div 4</div>
<p class="intro">This is a paragraph.</p>
<p class="intro">This is another paragraph.</p>

2
mcon On

If you're looking to remove the elements from the DOM, run the script like this:

$('div').on('click',function(){
    alert("Hello");
    $(".div1").remove();
    $(".intro").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">div 1</div>
<div class="div2">div 2</div>
<div class="div3">div 3</div>
<div class="div4">div 4</div>
<p class="intro">This is a paragraph.</p>
<p class="intro">This is another paragraph.</p>

removeClass('intro1') will remove the intro class property from the object. remove() is the function that will remove it from the DOM itself.