Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements with a single class in JQuery

I want to be able to select all elements that only have a single (given) class (and no other)

for example, let's say my page looks like this

<html>
    <body>
        <div class="a"> </div>
        <div class="a b"></div>
        <div class="c"></div>
    </body>
</html>

I want to be able to select only the first element - because it has a single class "a", and no other classes.

Thanks

like image 300
Gal Avatar asked Nov 22 '12 20:11

Gal


People also ask

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do you select an element with a class name example?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How can I select an element with multiple classes in jQuery?

The . class selector can also be used to select multiple classes. Note: Seperate each class with a comma. Note: Do not start a class attribute with a number.


1 Answers

How about this:

$('.a[class="a"]')

or as @Hexa propsed:

$('div[class="a"]')

http://jsfiddle.net/taYWP/

@Hexa: and it's actually the fastest! ;-) http://jsperf.com/attr-vs-attr-and-class

like image 127
zerkms Avatar answered Sep 23 '22 00:09

zerkms