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.
Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements.
The difference between Class and ID selector The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.
As you said, the ID is the faster lookup, but which one you chose has more to do with what you want to do. Think of a class like a category, or classification for different items that have a common or shared aspect to them, while an ID in contrast, has some unique property it is one of a kind.
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.
Obviously your first code using class is much cleaner, neater and better.
ID selector are the fastest, which is true.. but at this time and age, it doesn't really matter.
So don't get bothered so much with performance(unless it is a concern) and just use the one that is clean and maintainable.
oh btw, you don't even need that anonymous function. See below,
$("input.printing").on("click", printPdf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With