jquery IDs with spaces

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.


Solution 1:

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.

Solution 2:

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 $("[id='content Module']")

Similar thread > What are valid values for the id attribute in HTML?

Edit: How id differs in between HTML 4.01 and HTML5

HTML5 gets rid of the additional restrictions on the id attribute. The only requirements left — apart from being unique in the document — are that the value must contain at least one character (can’t be empty), and that it can’t contain any space characters.

Link: http://mathiasbynens.be/notes/html5-id-class

Solution 3:

Just in case anyone is curious, I found that escaping the space will work. This is particularly useful when you don't have control over the target DOM (e.g. from within a userscript):

$("#this\\ has\\ spaces");

Note the double-backslash, which is required.