top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between ID selector and class selector in jQuery?

+2 votes
934 views
What is the difference between ID selector and class selector in jQuery?
posted May 22, 2015 by Ankur Athari

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

for HTML

The id Selector

The id selector is used to specify a style for a single, unique element.

The id selector uses the id attribute of the HTML element, and is defined with a "#".

The class Selector

The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."

JQUERY:

he id selector uses document.getElementByID("theid") while the class selector uses document.getElementsByClassName("theclass") where available, document.querySelector() when the previous is not available, and then a for loop if neither of the previous are available. selecting by ID will always be faster than selecting by class, however, it is better to select by class and have re-used javascript code than to write a separate function for each id when they all do the same thing.

As a rule of thumb, If an id needs a -n, such as id="div-1" id="div-2" etc, then its better off using a class class="div"

answer May 22, 2015 by Shivaranjini
...