8

I am trying to make a css selector query for exact class name .

Consider this html

<div class="My class1">Some long text</div>
<div class="My class1 234">Some long text2</div>
<div class="My class1">Some long text3</div>
<div class="My class1 haha">Some long text2</div>

Now i want to catch only class 'My class1' ...and ignore the 'My class1 234' or 'My class1 haha'..

The query $$('div.My class1') , gives me all the 4 above . Note : I am trying on firebug console..

How to specify the exact class name here so to get only that particular class ?

Thanks

1
  • Do either of the answers match your requirements? If not, why not? Feedback is important. Commented Jun 26, 2013 at 8:23

3 Answers 3

14

jQuery equals selector: http://api.jquery.com/attribute-equals-selector/

jQuery("[class='My class1']").

or

$("[class='My class1']").

or

$$("[class='My class1']").
Sign up to request clarification or add additional context in comments.

2 Comments

Why are you assuming the OP is using jQuery? Especially considering the last line is not jQuery.
To be honest, I don't know which framework/class is represented by $$. jQuery is most common, and it works the same in mootools, see mootools.net/docs/core125/core/Utilities/Selectors
7

Attribute Selector Syntax

For straight CSS it is:

[class='My class1']

For most javascript frameworks like jQuery, MooTools, etc., it is going to be the same selector string used as for the straight CSS.

The key point is to use an attribute selector to do it, rather than selecting directly by the class name itself. The class= (with just the equals sign) will only select for an exact match of the string following. If you also have need of catching class1 My then you would need to select as well for [class='class1 My']. That would cover the two cases where only those two classes are applied (no matter the order in the html).

Comments

6

Class definitions in elements are separated by spaces, as such your first element infact has both classes 'My' and 'class1'.

If you're using Mootools, you can use the following:

$$("div.My.class1:not(div.234):not(div.haha)")

Example in Mootools: http://jsfiddle.net/vVZt8/2/

Reference: http://mootools.net/docs/core125/core/Utilities/Selectors#Selector:not

If you're using jQuery, you can use the following:

$("div.My.class1").not("div.234").not("div.haha");

Example in jQuery: http://jsfiddle.net/vVZt8/3/

Reference: http://api.jquery.com/not-selector/

These two examples basically retrieve all elements with the classes 'My' and 'class1', and then remove any elements that are a 'div' element which have the either of the '234' or 'haha' classes assigned to them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.