jQuery is a powerful JavaScript library that allows you to select DOM elements in numerous ways. Sometimes you may need to select element with multiple classes for your code. In this article, we will learn how to select element with multiple classes in jQuery.
How to Select Element With Multiple Classes in jQuery
Let us say you have the following elements on your page.
<div id='div1' class='a b'>...</div> <div id='div2' class='b'>...</div> <div id='div3' class='a'>...</div>
In jquery we use .className selector to select an element by its class name.
If you use the following jQuery selector, it will select both div1 and div3.
$('.a')
If you use the following jQuery selector, it will select both div1 and div2.
$('.b')
So how do we select only div1 without selecting div2 and div3. Here is the selector to be used for selecting element with both classes a and b in them.
$('.a.b')
Actually, the order of classes is not important in above selector. You can swap them and it will still work.
$('.b.a')
Please note there should not be any space between the two class selectors .a and .b. If you put space between the two class selectors, it would mean the element with second classname is nested within the element with first classname.
If you have the following DOM structure, you can use $(‘.a .b’) to select the inner div. In this case, you need to add space between .a and .b.
<div id='div1' class='a'> <div id='div2' class='b'>...</div> </div>
In this article, we have learnt how to select element with multiple classes using jQuery. It is important to mention all class selectors one after the other without any space in between.
Also read:
How to Show Last Queries Executed in PostgreSQL
How to Generate Random Color in JavaScript
How to Read from Stdin in Python
How to Download Large Files in Python
How to Remove All Occurrences of Value in Python List
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.