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. If we were dealing with monetary values, there are many individual figures, and some subtotals and but only one total. You may want to use a .figure class to format the styling of all the individual figures, a .subtotal class for each subtotal so you could style them differently, and you could assign an id to the total, because you want it to have unique styling, and there will only be one.
If you dynamically wanted to find all the values and convert them to a different currency, it would be a simple thing to find all the values and writing the code to convert them all at once would be trivial, while writing the code to find each number by id would be tedious at best and confusing.
So, it really depends on what you are trying to do. If you want to find one and only one item, an id is far faster, but if all the items have something in common, it is certainly simpler (and possibly faster) to reference them all by class instead. I would be curious to see a test result comparing those ...
Code to update all the values on click of a convert button after someone enters a conversion ratio:
$('#convertBtn').on('click', function () {
var factor = $('#convRatio').val();
var $err = $('#errorPanel');// only create once to save resources
if (factor) {
// remove any error condition
if ($err.text()) {
$err.text("");
}
// get an array-like object of all the values
var $vals = $('#total, .subtotal, .figures');
$vals.each(function () {
var $th = $(this);// only create once to save resources
var val = $th.text();
$th.text(val * factor);
});
} else {
$err.text("Please enter a conversion rate");
}
});
Code to highlight just the subtotals when you click on one of them:
var $subs = $('.subtotals');
$subs.on('click', function () {
var $sub = $(this);// only create once to save resources
if ($sub.hasClass('hilite')) {
$sub.addClass('hilite');
} else {
$sub.removeClass('hilite');
}
}
Code to highlight just the total when clicked:
var $tot = $('#total');// only create once to save resources
// toggle highlighting on and off when any subtitle is clicked
$tot.on('click', function () {
if ($tot.hasClass('hilite')) {
$tot.addClass('hilite');
} else {
$tot.removeClass('hilite');
}
}