4

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

zoranc
  • 2,410
  • 1
  • 21
  • 34
allencoded
  • 7,015
  • 17
  • 72
  • 126

3 Answers3

3

You can escape the square brackets with two backslashes

var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");
James Curtis
  • 146
  • 6
2

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>");
Barry Meijer
  • 760
  • 4
  • 16
0

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...

syymza
  • 679
  • 1
  • 8
  • 23