[FAQ] Common Problems for "Make an Interactive Website: News Reader"

Why do I have a dot (.) before a class name when selecting an element, but not when adding or removing it’s class?

When you select an HTML element, there are three main ways you can do that. By it’s tag name (tag), by one of it’s classes (.class), or by it’s id (#id). So, with these elements:

<div></div>
<div class="example-class"></div>
<div id="example-id"></div>

(the class or id name could be anything you want it to be)
you would select each element like this with jQuery, respectively:

$('div')
$('.example-class')
$('#example-id')

The character in front of your selection (nothing, ., or #) represents what selector it is. This is necessary because you might have a class name that’s the same as a tag name, for some reason.

However, addClass(), removeClass(), and toggleClass() don’t need that distinction. They know they’re dealing with a class, so the distinction between the various selectors isn’t necessary.


Additional reading

https://api.jquery.com/addClass
https://api.jquery.com/removeClass
https://api.jquery.com/toggleClass

8 Likes