Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element based on multiple classes

I have a style rule I want to apply to a tag when it has two classes. Is there any way to perform this without JavaScript? In other words:

<li class="left ui-class-selector"> 

I want to apply my style rule only if the li has both .left and .ui-class-selector classes applied.

like image 851
Ciel Avatar asked Mar 31 '10 16:03

Ciel


People also ask

How do you find an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Can you apply multiple classes to an element?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

How do you select multiple classes in HTML?

We can select use class selector or id selectors, But sometimes, we want to force to use class selector, example explains how to select multiple classes in CSS/HTML. Let's have a div class with multiple CSS class names. The div tag has multiple class names separated by space as given in the below example.


2 Answers

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 {     /* style here */ } 

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector {  } 

Official documentation : CSS2 class selectors.


As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

like image 145
Felix Kling Avatar answered Sep 22 '22 05:09

Felix Kling


Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB { /*style here*/ } 

Class & Id

.classA#idB { /*style here*/ } 

Id & Id

#idA#idB { /*style here*/ } 

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector { /*style here*/ } 

or

.left.ui-class-selector { /*style here*/ } 
like image 25
nidhi0806 Avatar answered Sep 19 '22 05:09

nidhi0806