Killua Zoldyck Killua Zoldyck - 2 months ago 9
Javascript Question

Using ampersand in a javascript string

My code looks as followed:

<script>

var array = ["test1", "test2", "test & test"];

$(document).ready(function() {

for (i = 0; i < array.length; i++) {
$("#" + array[i]).hide();
}

});

</script>


<ul>
<li id="test1"></li>
<li id="test2"></li>
<li id="test & test"></li>

</ul>


While using Javascript/JQuery I want to hide a few parts.
However this will give me a syntax error.

What do I do so I can compare the id from my listitem with the javascript string?
I already tried switching the ampersand in javascript with things like "&amp ;" and "&#38 ;"

Since I get the id of the listitem from a database I prefer not changing that side.

So anybody help me out here?

Answer

You can't use spaces in the id of an element.

You probably don't want to use an ampersand in the id of an element, but if you really need to you can escape the & using one backslash in the css selector, and two backslashes in the jQuery selector.

In your example:

var array = ["test1", "test2", "test\\&test"];

$(document).ready(function() {
  for (i = 0; i < array.length; i++) {
    $("#" + array[i]).hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul>
  <li id="test1"></li>
  <li id="test2"></li>
  <li id="test&test"></li>
</ul>