Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 729
anonymous Avatar asked Feb 04 '11 00:02

anonymous


People also ask

Can you use a variable in a jQuery selector?

Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

Can you use JavaScript variables in jQuery?

It's quite easy to use JavaScript variables in jQuery selectors.


2 Answers

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}`) 
like image 196
Ben Rowe Avatar answered Sep 30 '22 19:09

Ben Rowe


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) 
like image 37
Alan Christopher Thomas Avatar answered Sep 30 '22 18:09

Alan Christopher Thomas