0

I have some ths that I know the text value of. I want to apply a class to a certain list of these ths.

What I have works like a charm, I just want to see if there's a better way to write it.

   //Custom extended jQuery psuedo function to check if text() of elem is exactly some string (ensures it doesn't overwrite existing fn)
//Ref: https://stackoverflow.com/a/18462522/2402616
        $.expr[':'].textEquals = $.expr[':'].textEquals ||
        $.expr.createPseudo(function(arg) {
            return function( elem ) {
                return $(elem).text() === arg;
            };
        });

     const textsOfThsToAddClassTo = ['foo','bar','fizz',buzz'];

    //Here's where my question really is
    textsOfThsToAddClassTo.forEach(text => {
        $(`th:textEquals('${text }')`).addClass('my-class');
    });

I'm just wondering if there's a better way to write that forEach part. Like, if I can use a selector to only contain what's in the array. Thanks!

user2402616
  • 1,434
  • 4
  • 22
  • 38
  • 1
    well, uh, it'd be better to not use a custom psuedo selector, for starters. – Kevin B Jan 11 '22 at 21:35
  • 2
    a better way? how you do define better? It's better for me personally to not abstract out unnecessarily, so I might favor `$('th').each(function() { if (array.includes($(this).text().trim())) $(this).addClass('thing'); }` – Kinglish Jan 11 '22 at 21:54
  • @KevinB What's wrong with the custom pseudo selector? – user2402616 Jan 11 '22 at 22:17
  • using a custom pseudo selector means the selector can't be passed directly to querySelectorAll. At that point, you mightaswell skip that and go directly to a foreach where you have more control of the flow. – Kevin B Jan 11 '22 at 22:23

0 Answers0