Why selector works in first example, but fails in second one?
See jsfiddle.
<div id="hello[1][2]_world"> </div>
<textarea id="console"></textarea>
<script>
$(document).ready(function() {
//first example
$('#hello\\[1\\]\\[2\\]_world').html('01234'); //everything is OK
//second example
var iid = 'hello[1][2]_world';
iid = iid.replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\\\$&");
$('#console').val(iid); //see in textarea, the same string as from first
$('#'+iid).html('56789'); //not working! whyyyyyyyy? :)
});
</script>
The first string is “actually”
'#hello\[1\]\[2\]_world'.What happens is that you have to escape
\s in the first case so that the$()function receives\[and so on so that it knows that it should treat those characters as part of the id.In the second case you’re creating a string that’s
hello\\\\[1\\\\]\\\\[2\\\\]_world(as you have 4 backslashes in the replacement!) that becomes, after the backslashes have been escaped,hello\\[1\\]\\[2\\]_world.You can confirm this by adding these lines at the end (look in the JS console):
http://jsfiddle.net/qSpaK/7/