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.
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.
It's quite easy to use JavaScript variables in jQuery selectors.
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}`)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With