Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting elements with exotic id [duplicate]

I'm working on a legacy system that uses square brackets in id parameters. E.g.:

<select id="mySelect[]">
  <option value="1">Yadda</option>
  <option value="2">Yadda</option>
  <option value="3">Yadda</option>
</select>

jQuery (being javaScript) quite rightly complains when I try to use this id in, say,

$("#mySelect[]").append(options);

Given the fact that I can't change the legacy code and therefore I'm stuck with the existing id's (which may or may not be valid in any context), what would be a good way to work around this mess and let me select my elements?

like image 293
Frank van Wensveen Avatar asked Jul 09 '13 15:07

Frank van Wensveen


2 Answers

While using meta characters you have to escapse those.

$("#mySelect\\[\\]").append(options);

Jquery selector docs saying that

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.

If you don't want to escape it, you can use the selector

$( document.getElementById('mySelect[]')
like image 129
Suresh Atta Avatar answered Oct 01 '22 18:10

Suresh Atta


Try this way:

$("#mySelect\\[\\]").append(options);

You need to escape [ and ] as they are reserved jquery chars used in selectors.

Have a look at the jquery docs

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").

and a fiddle here

Plus ofcourse you could do this $('[id="mySelect[]"]') But since it is an attribute selector performance wise this will be slower and you lose the advantage of using the id selector, but handy if you are in no way to escape the chars.

like image 44
PSL Avatar answered Oct 01 '22 20:10

PSL