Ricardo Zea
Ricardo Zea

Reputation: 10283

jQuery: Use variables within selector

Mind you, I'm not a jQuery guru and just still learning.

I have this looong function:

$('.client1 > *:first-of-type, .client2 > *:first-of-type, .client3 > *:first-of-type, .client4 > *:first-of-type, .client5 > *:first-of-type').append('<span class="jsi"/>');

It does work, yes, but I know it's not efficient and not easily scalable because every time I have to add a new 'client' I have to add it to the selector list.

So I know I could use (a) variable(s) for the > *:first-of-type part, and maybe an "array" (I don't know if I'm saying that right) for the .clientX part.

This is honestly a bit over my head.

This is what I've tried but of course doesn't work:

var fot = "> *:first-of-type";
$('.client1' + fot, '.client2' + fot, '.client3' + fot, '.client4' + fot, '.client5' + fot).append('<span class="jsi"/>');

What happens is not only I would like to not have to repeat myself but be able to scale this more efficiently as new clients need to be added to the function.

Any help on this is greatly appreciated.

Upvotes: 0

Views: 101

Answers (1)

dersvenhesse
dersvenhesse

Reputation: 6404

Just add an extra class, like client and you don't need all that stuff anymore.

<div class="client client1">..</div>
<div class="client client2">..</div>

So you can select all elements with class client.

$('.client > *:first-of-type').each(function() {
    $(this).append('<span class="jsi" />');
});

Upvotes: 3

Related Questions