Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add variable inside jQuery selector

Tags:

jquery

Good Day

I want to add a variable into a jQuery selector, but the syntax is wrong:

var c = $(this).attr('class');

            if ($('#articleThumb ul li img').hasClass(c)) {
                $('#articleThumb ul li img.'+c').clone().appendTo('#articleFeatured');
            }

the class

img.class is a variable and not a constant like img.birds for example...

Thank you

like image 207
David Van Staden Avatar asked Mar 22 '13 10:03

David Van Staden


3 Answers

Your quotes are off, notice the stray one after c. It should be:

$('#articleThumb ul li img.' + c)
like image 188
Grant Thomas Avatar answered Oct 21 '22 23:10

Grant Thomas


You can simply concatenate the variable with selector string. Remove the extra single quote at the end of c in selector.

Change

 $('#articleThumb ul li img.'+c')

To

$('#articleThumb ul li img.' + c)
like image 20
Adil Avatar answered Oct 21 '22 23:10

Adil


Looks like you're adding an additional '

$('#articleThumb ul li img.' + c)
like image 2
Darren Avatar answered Oct 22 '22 00:10

Darren