anonymous
anonymous

Reputation: 1539

jQuery selectors with variables

How to mix variables with selectors?

I have ID variable.

I want to select image with this id from div #one.

jQuery('#one img .id') is the selector. I've tried $('#one img .'+id) but doesn't work.

Upvotes: 47

Views: 79722

Answers (5)

Ben Rowe
Ben Rowe

Reputation: 28711

Edit: Based on your comment below, you would use this:

$('#one img.'+id)

In your question you have a space between img and the .class, I've simply removed that so you get img.className or img.'+className

With the introduction of template literals in ECMAScript 2015, you can also do

$(`#one img.${id}`)

Upvotes: 56

RollingInTheDeep
RollingInTheDeep

Reputation: 731

ID's should be unique in your HTML. So you should be able to select the ID directly without worrying about which DIV it is in. Since you mention the ID is attached to the img tag, then this should be enough.

$('#' + id);

Upvotes: 2

Joko Wandiro
Joko Wandiro

Reputation: 1987

Maybe you want to select img which set with specific class and save this class into id variable within div element with id='one'.

DEMO

In demo i select img element, clone it, and append to div id=one.

Upvotes: 0

Chris Laplante
Chris Laplante

Reputation: 29658

. is a class selector. Try changing that to a #:

$('#one img #'+id)

Upvotes: 3

Alan Christopher Thomas
Alan Christopher Thomas

Reputation: 4550

This might just be a typo or you actually use the id variable in a class, but maybe it should be:

jQuery('#one img #'+id)

Upvotes: 3

Related Questions