jona jona - 8 days ago 7
CSS Question

How to run a for loop inside a jQuery selector?

I am programming a WebExtension for Facebook which will invoke CSS based on their privacy settings.

$(document).ready(function(){
$("a[data-tooltip-content*='Public']").closest(".userContentWrapper._5pcr").css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest(".userContentWrapper._5pcr").css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest(".userContentWrapper._5pcr").css({"background-color": "cyan"});
$("a[data-tooltip-content*='Public']").closest("._2tdc").css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest("._2tdc").css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest("._2tdc").css({"background-color": "cyan"});


However, I noticed that a different page layout are has a different class value that I need to invoke with CSS codes.

Is there any way to write a
for
loop inside a jQuery selector?

$("a[data-tooltip-content*='Public']").closest("**For(a list of class name), loop through all of them)**").css({"background-color": "yellow"});


I have tried using
$.each
jQuery, but I really don't have much of an idea after reading through the documents.

var obj = {".userContentWrapper._5pcr" , "._2dc"};

$.each(obj, function(index,element)){
$("a[data-tooltip-content]").closest(obj).css({"background-color": "violet"});
$("a[data-tooltip-content*='Public']").closest(obj).css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest(obj).css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest(obj).css({"background-color": "cyan"});
}


Sample result (original image link):

sample result

Answer

This should be as easy as storing all the class names in an array, and using a loop

var classses = ['.class1','.class2'];
for(var i=0;i<classes.length;i++)
   $("a[data-tooltip-content*='Public']").closest(classes[i]).css({"background-color": "yellow"});

However, in general, multiple selectors can be separated with commas so this may also work.

$("a[data-tooltip-content*='Public']").closest('.class1, .class2')
                                      .css({"background-color": "yellow"});