144

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.

Jeff Davis
  • 4,736
  • 4
  • 38
  • 44
  • @Glavić All of your statements are true. However, the newly accepted answer will be more helpful to people who really need this solution. For those who are really stuck, knowing how to deal with spaces is what they really need. – Jeff Davis Nov 08 '13 at 14:44
  • Yes, that is true, but my answer also has solution for ID's with spaces, it is even bolded out ;) – Glavić Nov 08 '13 at 17:01
  • 1
    Upvote for correctly writing IDs instead of ID's. Sorry, pet peeve. And yes, I know most people use an apostrophe to pluralize acronyms and shortened words, but it still looks like a grocer's apostrophe to me http://walkinthewords.blogspot.com/2009/05/grocers-apostrophe.html – Ruan Mendes Jul 08 '14 at 14:49

11 Answers11

282

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.

Community
  • 1
  • 1
Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44
  • 1
    even the answer from Glavic is best suggestion. i think this answer solved the problem :) – GusDeCooL Apr 22 '11 at 07:57
  • 9
    This helped me out a LOT. I am reading in some terrible HTML via ajax and have no control over the structure of the HTML or format of the IDs. Their IDs have spaces in them, so Elliot's answer helps tremendously, whereas glavic's offers no help at all. – daybreaker Jun 27 '11 at 18:59
68

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

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • 4
    +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 Feb 27 '09 at 19:58
  • 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 Feb 27 '09 at 20:00
  • 1
    You’re quoting the HTML 4.01 spec here. While it’s still not allowed to use space characters in ID attribute values, HTML5 does get rid of most of these restrictions: http://mathiasbynens.be/notes/html5-id-class – Mathias Bynens Oct 24 '11 at 08:39
  • 3
    Don't tell the man to go through and hack up the whole codebase of an old project just because "standards". At most, this should rate a comment, certainly not the accepted answer :( – Coderer Apr 02 '13 at 11:55
  • Funny. Spaces work just fine for most purposes, why make them unstandard? – Lodewijk Sep 24 '14 at 22:31
  • @Glavić, #content\ Module? It's definitely not going to be pretty. I can't recall but I came here because I wanted to use spaces. – Lodewijk Jul 29 '15 at 20:07
32

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.

Morgon
  • 3,269
  • 1
  • 27
  • 32
9

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

var element = document.getElementById('content Module');
$(element) ... ;
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
2

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

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
Chris Klepeis
  • 9,783
  • 16
  • 83
  • 149
  • 1
    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 Feb 27 '09 at 20:01
  • 1
    Wouldn't `$(document.getElementByID("content Module"))` give you a jquery object? – gotomanners Jan 16 '13 at 09:55
1

This worked for me.

document.getElementById(escape('content Module'));
Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
xxx
  • 11
  • 1
0

this can work if you want the element have the exact value for the id

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

but if you want to check if element have only one of them ( just like class ) with or without other ids

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

this will select the element if it has id="content" or id="content Module" or id="content Module other_ids"

Robert
  • 2,342
  • 2
  • 24
  • 41
0

I found for my case that escape did not work because it replaces spaces with %20. I used replace instead e.g. to replace the h1 of the page with the text of a list item. If the menu contains:

<li id="Contact Us"\>Contact Us</li>

function setTitle(menu) {
    $("h1").text( $("li#" + menu.replace(" ", "\\ ")).text() );
}
Martin
  • 2,316
  • 1
  • 28
  • 33
0

I was having issues with element ids containing commas and/or spaces in jQuery, so I did this and it worked like a charm:

var ele = $(document.getElementById('last, first'));

This has spaces and does not work:

var ele = $('#last, first');

This has comma and does not work:

var ele = $('#last,first');

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

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>
Donovan P
  • 591
  • 5
  • 9
0

While it’s technically invalid to have a space in an ID attribute value in HTML, you can actually select it using jQuery.

See http://mothereffingcssescapes.com/#content%20module:

<script>
  // document.getElementById or similar
  document.getElementById('content module');
  // document.querySelector or similar
  $('#content\\ module');
</script>

jQuery uses a Selectors API-like syntax, so you could use $('#content\\ module'); to select the element with id="content module".

To target the element in CSS, you could escape it like this:

<style>
  #content\ module {
    background: hotpink;
  }
</style>
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248