Reputation: 4167
in my program i have a jquery line
$( '#monsters[0]').animate( { left: "+=25" },500);
i have a array called monsters, but i dont see why that would make a difference, this code does work when i change the id to a different images id, and i put ('img')
instead it even works on the image with the id monsters[0]
i am also sure this is the images id. however i run the above code and nothing happens to the image, no error appears in the console either, can anyone explain this?
link here, if that helps at all.
Upvotes: 0
Views: 121
Reputation: 382150
'#monsters[0]'
can't be parsed by jQuery as meaning the element has an id "monsters[0]"
. It's parsed as a query for an element having as id monsters
and an attribute 0
.
You may do
$(document.getElementById('monsters[0]')).animate( { left: "+=25" },500);
If you use it more than once you can build yourself a small utility :
function $$(id) { return $(document.getElementById(id)) }
so that you only have to do
$$('monsters[0]').animate( { left: "+=25" },500);
But you should probably avoid those id, they would for example bring you the same problem in CSS. Here it looks like a class or a data attribute would make more sense.
Comment :
There's of course the other solution of dynamically escaping the [
and ]
characters (and later on the other ones that could arise). Don't do it : this makes the code much more complex, hides the fact that it works only for certain forms of id, and is much heavier : you build a string that jQuery will parse to understand you need the id and then jQuery will call document.getElementById
. Direcly use document.getElementById
to be clearer, more reliable and more efficient.
Upvotes: 2
Reputation: 1567
$( '#monsters').animate( { left: "+=25" },500);
will do.
$( '#monsters')
gives away a jQuery wrapped object.
Upvotes: -4
Reputation: 943564
The characters [
and ]
have special meaning in a selector (they indicate an attribute selector). If you want to use them as part of an ID selector (or any other kind of selector) you have to escape them with a \
.
Note that since you are expressing your selector as a string literal, you have to escape the escape sequences too.
'#monsters\\[0\\]'
Upvotes: 5