0

I am trying to remove a class and add a class to divs using jQuery but it doesn't seem to be working.

My html is like this:

<div id="foo">
  <div class="row">
    <div class="col-sm-4">
        <h4>one</h4>
    </div>
    <div class="col-sm-4">
        <h4>two</h4>
    </div>
  </div>
</div>

I would like to remove the class col-sm-4 and instead add class col-sm-6

This is what I've done:

$("#foo").find(".col-sm-4").addClass(".col-sm-6").removeClass(".col-sm-4");

I've ensured that I am getting elements back by find

alert($("#foo").find(".col-sm-4").length); //2

Even though I'm not getting any errors, there is no change in my elements.

8
  • 1
    I wish jQuery would automatically strip out a leading . in the addClass() and similar methods. I myself make this error all the time. Commented Jun 10, 2014 at 15:31
  • Some basic debugging with the console, and reading the docs for the proper syntax for addClass and removeClass would've solved your problem. Commented Jun 10, 2014 at 15:31
  • While you were doing it wrong, it does actually work Commented Jun 10, 2014 at 15:32
  • arghhh stupid me. I found the problem (adding .) after posting the question. Thanks! Commented Jun 10, 2014 at 15:33
  • 1
    @Novocaine88 It doesn't really work, does it? If it did, the text in this example would be red. Commented Jun 10, 2014 at 15:35

3 Answers 3

5

You do not need to include the . in the col-sm-6 of the .addClass parameter; nor do you need to use .find().

The following will work:

$("#foo div.col-sm-4").addClass("col-sm-6").removeClass("col-sm-4");
Sign up to request clarification or add additional context in comments.

Comments

1

When you are using the methods addClass and removeClass, don't use the period to indicate the class name, so you should write

$("#foo").find(".col-sm-4").addClass("col-sm-6").removeClass("col-sm-4");

Comments

0

1) ".col-sm-6" is an example of a JQuery selector - Which, from the JQuery site is: "Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document." The methods addClass and removeClass are functions that except a class name to add or subtract to the element's class attribute. You wrote it like a JQuery selector. You are using the concept of selectors correctly when you reference your object with the JQuery selector $("#foo div.col-sm-4").

2) You say: "Even though I'm not getting any errors, there is no change in my elements." - This is a great observation. You should know that much of JavaScript fails silently. Between 1 and 2 of this answer, I highly recommend the book JavaScript: The Good Parts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.