jquery IDs with spaces

Viewed 101958

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.

11 Answers

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.

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

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

var element = document.getElementById('content Module');
$(element) ... ;

An idea to try:

$("#content" + &amp;#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, try document.getElementByID("content Module")

This worked for me.

document.getElementById(escape('content Module'));

Escaping any misc character on selector (along with spaces).

var escapeSelector = function(string) {
  string = string||"";
  if (typeof string !== 'string') return false;
    return string.replace( /(:|\.|\[|\]|,|=|@|\s|\(|\))/g, "\\$1" );

}
console.log($("div[data-id="+escapeSelector("Document (0).json")+"]").text());   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-id="Document (0).json">Howdy</div>

Related