For example, on a site like this
How can I code something that will highlight any prices above €20 red within the product grid? Also, I need it to continue to work even when users select/deselect categories on the right.
Would this be JavaScript?
$('div').each(function() {
$(this).find('.mErEH _223RA').sort(function(a, b) {
return b.innerText - a.innerText;
}).slice(0, 5).addClass('higherthan20')
});
.higherthan20 {
color: red;
}
2
Answers
You can add classes to element using its classList properties
Your code would now be something like this:
If you want to conditionally add color to text, your code can become like this:
The site referenced, filters prices by displaying only prices that meet a range defined by the user while removing any prices not within the price range. The filter you requested just highlights anything more than 20. Moreover, the second request:
is impossible to answer since you haven’t posted any code involving any of the other filters.
Concerning the code that was posted, it fails not only syntactically, but in purpose as well.
jQuery methods do not recognize plain JavaScript references and vice versa. In order to use a plain JavaScript method on a jQuery object, the jQuery object must be dereferenced. Avoid chaining jQuery and JavaScript methods. Below is a table of jQuery methods and a table of plain JavaScript methods used in the question:
jQuery Methods
Plain JavaScript Methods
In short, the jQuery object consisting of all
div.mErEH _223RA
is created by.each()
and.find()
. Then the function fails when.sort()
is called on said jQuery object because:.sort()
is a plain JavaScript method which does not recognize jQuery objects.sort()
deals with arrays, of which jQuery objects are notIf the function were to forgo jQuery all together and just collect all
div.mErEH _223RA
as a NodeList and then convert into an array,.sort()
and.slice()
will work. Unfortunately, a new array that consists of the first 6 DOM elements in ascending order is returned which is not even close to highlighting all DOM elements with over 20.In the following example, the actual HTML layout is irrelevant, the className
".x"
should be replaced with".mErEH _223RA"
.Details are commented in example