JoyceLee JoyceLee - 1 month ago 6
jQuery Question

Select elements with multiple classes in jQuery

If an element has multiple classes like this:

class="btn btn-primary add-movie-button is-on"


can I select it only by one class name using jQuery like:

$(".add-movie-button")


Can I use
.hasClass("is-on")
for this element?

Answer

With a class on an element like so: class="btn btn-primary add-movie-button is-on"

You can select by one or more than one class. Adding more classes increases specificity.

For example:

$(".add-movie-button")

is less specific than

$(".add-movie-button.is-on")

In either case you can use the hasClass returning a boolean;

var isClassy = $(".add-movie-button.is-on").hasClass("is-on");
var isSmallClassy = $(".add-movie-button").hasClass("is-on");

Note that this would return true if ANY element matched the conditions. If you desire to see if ALL do then use length:

var longClasses = $(".add-movie-button.is-on");
var shortClasses = $(".add-movie-button");

var both = longClasses.length === shortClasses.length;
Comments