Reputation: 2084
When looking through jQuery examples, I see CSS classes referred to with a prepending "." sometimes and other times without. For example, in this snippet from codecademy:
else if(event.which === 110) {
var currentArticle = $('.current');
var nextArticle = currentArticle.next();
currentArticle.removeClass('current');
Why is the selector $('.current') needed in the 2nd line, but only ('current') is required in the 4th line?
Upvotes: 2
Views: 267
Reputation: 12127
jQuery selectors have designed on CSS property, so same syntax could be used, you can also use class
selector different way like $("[current]") it will work as HTML
tag element properly.
function removeClass()
not taking class as selector, the function announce that is only use for class properly so no need to determine passing value, although the function is taking value as string not <selector>
Upvotes: 0
Reputation: 2017
removeClass()
AND $('.current')
are both method and you can pass parameters to an method, the only thing is that its the convention that jQuery
uses. Try naming you class as <div class='.current'>I am a div</div>
and try this console.log($('..current').text());
you will have this error Error: Syntax error, unrecognized expression: ..testA
so basically its the rules / conventions of jQuery.
Upvotes: 0
Reputation: 8623
I think
var currentArticle = $('.current');
here you need a dot because it means you select it by class matching.
and in below:
currentArticle.removeClass('current');
you already specify to remove a class, you don't need a dot, because here it isn't a selector, it is the class name you want to remove.
Upvotes: 0
Reputation: 3923
The method explicitly uses the term Class.
Otherwise, you will always need a class selector, if that's your approach to targeting an element (you can target by ID, data attributes, HTML tags).
Upvotes: 0
Reputation: 16626
That is a convention.
On the 2nd line $('.current') is telling the jQuery to search for something called "current" and the dot specifies it as a class. So we need to call ".current"
On the 4th line, you're already telling jQuery that you are going to select a class by using "removeClass" so you don't need to use the dot there. Because that would be like "removeClass current being a class"
Upvotes: 1
Reputation: 388316
In $('.current')
(or in methods like find/next etc where you are trying to find an element with the given class), we are using a selector, so the notation for class selector is preceeding .
has to be used.
When when you add/remove/toggle a class, you are not using a selector, you are just using a name so there is no .
used
Upvotes: 1