I want to toggle a class based on some condition which I have to compute from the ID of the processed element:
$(".centre li").toggleClass("highlight", someFunction(x));
(This will select about 10 list elements. I need each element’s ID to look up if it requires highlighting or not.)
someFunction(selectedElement) {
if (selectedElement.id in someArray)
return true
else
return false
}
I might have lost my way in closure-hell, but this in the function is set to another element. This is the real code:
...
showListItem = function(linkSelector, listSelectors, contentSelector) {
return function() {
$(".centre li").toggleClass("backgroundFullOrange", test(this));
function test(a) {
console.log($(a).attr("id")); // -> id of the linkSelector-element
}
}
};
$(linkSelector).bind('click', showListItem(linkSelector, listSelectors, contentSelector))
...
Update: turned out that toggleClass() was not the function I’ve been looking for. See accepted answer for correct usage.
First,
$(".centre li").toggleClass("highlight", someFunction(x));is not a correct syntax. The 2nd arg isswitchand the definition is as below,switch cannot be a function as you have.
In your case you going to have to call
.removeClass('highlight')and thenaddClassinside which you can compare the ID of the element and return highlight or ”.See DEMO which randomly highlights 2 li’s every 1.5 secs.
DEMO
I think I understood it correctly this time. See below,
DEMO
Try using
.filter. Something like below,The highlight will be added only to those elements that are returned by the filter.