tags:

views:

1273

answers:

4

Does anyone know how to select an item in the DOM by ID with jQuery, when that ID has a space?

For example, the id of my item would be

<div id="content Module">Stuff</div>

How would I select this with jQuery?

If I just do

$("#content Module").whatever() 

jQuery will try to find an item with both the id of content and the id of Module, which is not what I am looking for.

I should add that I am working with an old code base where these two word ids are used extensively, so going through and changing all the ids would be bad.

However, as mentioned in the comments of the selected answer, I can just truncate anything after (and including) a space on display, this has solved the problem.

Thanks.

+11  A: 

Don't use spaces, the reason for this is simple, space character is not a valid for ID attribute.

ID 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 (".").

But if you don't care about standards try $('#content%20Module'), but I think it will not work...

Similar thread > http://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html

glavić
+1. Following the naming standards and then you don't have to come up with workarounds for when you don't follow them.
matt b
This triggered the idea of truncating the second word on display so that I have valid ids. Took care of the issue, thanks!
Jeff Davis
A: 

An idea to try:

$("#content" + &#032; + "Module").whatever()

$("#content" + %20 + "Module").whatever()

the semicolon may cause a javascript error.... I also recommend changing the ID to not have any spaces.

Also, have you just tried document.getElementByID("content Module") ...

Chris Klepeis
This did not work, but it was a good idea.
Jeff Davis
document.getElementByID would give me the regular object and then I could not do the jQuery functions I am looking for. However, in similar circumstances that would be a good work around.
Jeff Davis
+1  A: 

The method Chris suggested can likely be adapted to work with jQuery functions.

var element = document.getElementById('content Module');
$(element) ... ;
ceejayoz
I didn't know that. Thanks.
Jeff Davis
+4  A: 

Use an attribute selector.

$('[id=content Module]').whatever();

Or, better, specify the tag as well:

$('div[id=content Module]').whatever();

Note that unlike $('#id'), this will return multiple elements if you have multiple elements with the same id within your page.

Elliot Nelson