Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery div addclass

Tags:

jquery

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 :-)

like image 356
June Avatar asked Jan 16 '23 21:01

June


1 Answers

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.

  • What are valid values for the id attribute in HTML?

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 '\\ '

  • DEMO
like image 150
calebds Avatar answered Jan 31 '23 05:01

calebds