JQuery not working

I am trying to add an html element, but for some reason it does not allow me to do this when the element has [0]in its 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, is it not added? What is the workaround for this?

Code can also be found in fiddle.

+4
source share
3 answers

You can avoid square brackets with two backslashes

var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");
+3
source

When you use square brackets in your ID, you should avoid them in jQuery with \ You can read more about using special characters in your selectors here (second paragraph): http://api.jquery.com/category/selectors/

JSFiddle: http://jsfiddle.net/Yye2L/7/

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

The square bracket indicates the attribute selector in jQuery. For this reason, you should not use square brackets as part of the identifier.

You can have the same code without parentheses 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 code, you can use:

var id = "#" + "stuff\\[0\\]";
$(id).append("<p>HI</p>");

which is not very elegant, but does the job ...

0
source

Source: https://habr.com/ru/post/1531197/


All Articles