I believe it is the jQuery contains
predicate you are looking for. It lets you search a string to find only nodes that contain a given string.
Assuming your items for sale have class item
, this code will add various more detailed classes at runtime:
$(".item:contains('pick-up')").addClass("pickup");
$(".item:contains('hatch')").addClass('hatchback');
Here is a live demonstration.
I have found that "searching for strings and adding CSS classes at runtime" is an effective--if not entirely elegant--way of patching "dirty data" and updating the output of code that I do not control. One ugliness to this is that the jQuery contains
test is case-sensitive. So the above code would match items containing text "pick-up"
but not text "Pick-up"
. It can be handy to use an alternate predicate that folds case (i.e. considers upper case and lower case equivalent). Here is the code that I use to add a containsfc
predicate to jQuery:
// add folded-case (i.e. case insensitive) extension to jquery contains pseudo-attribute
jQuery.expr[':'].containsfc = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
Then your search becomes:
$(".item:containsfc('pick-up')").addClass("pickup");
But "dirty data" often has a lot of different variations, like the difference between "pick-up"
and "pickup"
. So here is an even more aggressively folding predicate, that removes all non-alphabetic spaces during comparison (and folds case as well):
// add folded extension to jquery contains pseudo-attribute
// to make case-insensitive and also ignore non-alphabetic characters
jQuery.expr[':'].containsfolded = function(a, i, m) {
return jQuery(a).text().replace(/[^A-Za-z]/g, "").toUpperCase()
.indexOf(m[3].replace(/[^A-Za-z]/g, "").toUpperCase()) >= 0;
};
Search then with:
$(".item:containsfolded('pick-up')").addClass("pickup");
to match just alphabetic characters. You may salt the included replace
function to taste, to keep or eliminate whatever characters you think relevant. Here is a live demo of the inclusive search function.
While this kind of string search and patch approach is imperfect, it often gets the job done, and doesn't require you to have control over the source of the data, or be responsible for its purity.