JQuery class selector vs id selector

Chun ping Wang picture Chun ping Wang · Mar 13, 2013 · Viewed 11.9k times · Source

I have 7 different buttons that all perform the same javascript function on click. should i use class selector or id selector.

$("input.printing").on("click", function(event) {
     printPdf(event);
});

or

   $("#package1Pdf").click(function(event) {
         printPdf(event);
   });
$("#package2Pdf").click(function(event) {
         printPdf(event);
   });
$("#package3Pdf").click(function(event) {
         printPdf(event);
   });
$("#package4Pdf").click(function(event) {
         printPdf(event);
   });

What are the advantage and disadvantage of each? Which is more preferred.

Answer

BinaryTox1n picture BinaryTox1n · Mar 13, 2013

You can use an ID filter without multiple selectors:

$('[id^="package"]').click(printPdf);

The above will select all id's starting with "package". This means the difference is mostly semantic. You should choose that which is most meaningful to your application and the way it was developed.

See the jQuery attribute selectors page to learn about the flexibility of jQuery selection. Keeping a bookmark on this page will prevent you from ever having to write code like your second example again.

Which is better?

If you have your structure set up so that you have a class that logically and correctly defines the appropriate set of elements, then that is what you should use to select on.

Likewise, if you have instead given elements specially named IDs and do not have a descriptive class name attached that represents what you want to select, then use the ID selection. The performance difference will be of no concern to almost any application, yours included.