Reputation: 4777
I'm currently working on the codecademy course on building an interactive website and I stumbled upon an ambiguity concerning the use of the elemement/class selection of the css elements.
javascript:
var main = function() {
$('.article').click(function() {
$('.article').removeClass('current');
$('.description').hide();
$(this).addClass('current');
$(this).children('.description').show();
});
};
css:
.current .item {
background: rgba(206,220,206,.9);
}
Why do I have to use the element selector 'current' instead of the class selector '.current' in line 4? Is there any rule behind it or just a specification of jquery?
Upvotes: 2
Views: 159
Reputation: 36703
Simply because the name of the class is current
not .current
, and in
$('.article').removeClass('current');
current
is not any selector but just a classname
which you want to remove, instead the selector is .article
.
You are thinking that we are using element selector instead of class selector. But you are wrong. Do you see the word Class in removeClass and addClass ? It means you are passing class selector, not element selector as an argument.
Now you may ask why don't you see dot with current? Because classes are specified using dot. Actually we have already specified that we are passing Class Selector, as you can see word "Class" in removeClass and addClass .
Upvotes: 10
Reputation: 1477
In line 4, you are not using 'current' as a selector, it is a class name. Whenever you use some class name as a selector( for example in .find('.current'), $('.current') , closest('.current') etc) then only the rule of putting
.for class name
#` for id etc are used. And whenever you are checking some class exists( .hasClass()), adding and removing a class(addClass('current'), removeClass('current'),then you have to mention correct class name. I hope it helps.
Upvotes: 0
Reputation: 17795
The addClass
and removeClass
methods accept one or more space-separated classes to be removed from the class attribute of each matched element. The name of the calss you want to add/remove is "current", not ".current"
http://api.jquery.com/removeclass/
http://api.jquery.com/addclass/
Upvotes: 0
Reputation: 9123
The function name removeClass() implies you have to state a class name. Using a selector you have to specify either you want to select a class or an ID.
Upvotes: 1
Reputation: 82241
as per docs addClass()
:
Adds the specified class(es) to each of the set of matched elements.
Hence, you need to pass the classname/names as parameter and not class selector built out of it.
Upvotes: 1
Reputation: 665546
In addClass
/removeClass
you use a class name (like the one you'd specify in the class
attribute of your html), not a DOM selector like in $()
.
Upvotes: 1