6

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

3 Answers 3

8

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

$('#articleThumb ul li img.' + c)
Sign up to request clarification or add additional context in comments.

2 Comments

One more question: If there is more than one element that has a specific class, how do I append only the first one?
@DavidVanStaden You can use eq(0) in your selector, such that: $('#articleThumb ul li img.' + c + ':eq(0)')
2

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)

5 Comments

One more question: If there is more than one element that has a specific class, how do I append only the first one?
$('.classname:first') will give you first element
yeah but the loop that the append function will run each time a specific class is found...so it will not listen to the :first selector inside the append function...since the append function will execute again
Sorry, could not get you, can you make a fiddle?
As Grant Thomas pointed out - you can use: $('#articleThumb ul li img.' + c + ':eq(0)') to prevent copies/redundancy
2

Looks like you're adding an additional '

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.