Terrence Brannon
Terrence Brannon

Reputation: 4968

What does jQuery's removeClass method return?

I am confused about these lines of JQuery:

if ($(ui).hasClass("color1"))
    $(ui).removeClass("color1").addClass("color2")
else
    $(ui).removeClass("color2").addClass("color1")

in this code.

I know that $(ui) is creating a JQuery instance. I would like to know if .hasClass is testing the entire DOM tree of the JQuery instance for any element which has color1 as part of its class attributes.

Also, the docs for removeClass do not state what removeClass returns. They do so allegorically with this code:

$("p").removeClass("myClass noClass").addClass("yourClass");

But I would prefer an explicit statement about what removeClass() returns. Because my second questions is: what is returned by removeClass and how is addClass can making use of it?

Upvotes: 1

Views: 818

Answers (3)

Markus Coetzee
Markus Coetzee

Reputation: 3444

It returns the jQuery object. See the documentation of the removeClass function: http://api.jquery.com/removeClass/

And the jQuery object: http://api.jquery.com/Types/#jQuery

Excerpt from the documentation of the jQuery object:

A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements".

Upvotes: 4

epascarello
epascarello

Reputation: 207527

Look at the documentation for removeClass, it tells you Returns: jQuery


enter image description here

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113455

It returns the elements you selected using the query:

$("[some query here]").removeClass("...").text("the text that must be set");

So, adding class1 and removing class2 can be done like bellow:

$("query .class2")
    .removeClass("class2")
    .addClass("class1");

On the documentation page you can see: Returns: jQuery.

Upvotes: 2

Related Questions