June
June

Reputation: 59

jQuery div addclass

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

Answers (2)

Chandra Sekhar
Chandra Sekhar

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.

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")
  • In HTML, all values are case-insensitive.
  • Must contain at least one character (can’t be empty), and that it can’t contain any space characters.

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

calebds
calebds

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

Related Questions