Reputation: 59
I have the following code to add active class to selected div:
$("div #"+ myID).addClass( "active" );
this only works when myID is one word, when myID has space in it, the code broke, I tried to wrap myID with quote, does not work.
Lots of the content have div id with space, since I'm not the content owner, don't have control to correct the content, I can only modify my code to work with the content. Is there any way to point to div id with space? thank you.
Problem solved. thank you all :-)
Upvotes: 4
Views: 571
Reputation: 16516
$("div #"+ myID).addClass( "active" );
Simply above code not valid
HTML5 Global id
Attribute:
The id attribute specifies a unique id
for an HTML element (the value must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id
.
Example: In HTML5 below id's are valid.
<p id="#">Foo.</p>
<p id="##">Bar.</p>
<p id="♥">Baz.</p>
<p id="©">Inga.</p>
<p id="{}">Lorem.</p>
<p id="“‘’”">Ipsum.</p>
<p id="⌘⌥">Dolor.</p>
<p id="{}">Sit.</p>
<p id="[attr=value]">Amet.</p>
<p id="++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.">Hello world!</p>
In jQuery: jQuery does handle any valid ID name. We just need to escape meta-characters (dots, semicolons, square brackets...etc). (like java-script having problem with quotes).
While using id in jQuery has below limitations.
// Does not work
$("#some:id")
// Works!
$("#some\\:id")
// Does not work
$("#some.id")
// Works!
$("#some\\.id")
See the reference here
Upvotes: 1
Reputation: 26228
Element ID's should not have spaces.
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
From HTML spec.
If the element ID is out of your control, escape spaces with \\
in your selector:
<div id="target element"></div>
$('#target\\ element').doSomething(); // escape invalid chars with \\
In your case, you'd have to replace spaces in myID with '\\ '
Upvotes: 8