Reputation: 7285
I am trying to append to a html element, but for some reason it doesn't appear to allow me to do so when the element has [0]
in its id name.
HTML
<div id="stuff[0]">
<div id="tag">blah</div>
</div>
<div id="stuff[1]">
<div id="tag">blah</div>
</div>
JQUERY
var id = "#" + "stuff[0]";
$(id).append("<p>HI</p>");
When I run the code it doesn't append? What is the workaround for this?
Code can also be found in the fiddle
Upvotes: 4
Views: 5050
Reputation: 760
When you are using square brackets in your ID's you should escape them in jQuery with \ You can read more about using special characters in your selectors here (second paragraph): http://api.jquery.com/category/selectors/
Here i updated your code on JSFiddle: http://jsfiddle.net/Yye2L/7/
var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");
Upvotes: 2
Reputation: 146
You can escape the square brackets with two backslashes
var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");
Upvotes: 3
Reputation: 689
The squared bracket indicates an attribute selector in jQuery. For this reason you are not supposed to use squared brackets as part of the id.
You can have the same code without brackets, if you must:
<div id="stuff0">
<div id="tag">blah</div>
</div>
<div id="stuff1">
<div id="tag">blah</div>
</div>
var id = "#" + "stuff0";
$(id).append("<p>HI</p>");
If you do not want to change the HTML you can use:
var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");
which is not very elegant but does the job...
Upvotes: 0