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
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.
In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).
Exact Value Match - The value contained within the attribute exactly matches the value entered. Contains Value Match - The value of the attribute contains the value entered. Subcode Match - Allows subcode matching that will match the value entered or that value with a hyphen and a subcode.
The class selector selects HTML elements with a specific class attribute.
jQuery equals selector: http://api.jquery.com/attribute-equals-selector/
jQuery("[class='My class1']").
or
$("[class='My class1']").
or
$$("[class='My class1']").
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With