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.
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:
Just in case anyone is curious, I found that escaping the space will work, and probably works best. This is particularly useful when you don't have control over the target DOM (i.e. a userscript):
Note the double-backslash, which is required.
This worked for me.
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');
Use an attribute selector.
Or, better, specify the tag as well:
Note that unlike $('#id'), this will return multiple elements if you have multiple elements with the same id within your page.
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:
jQuery uses a Selectors API-like syntax, so you could use
$('#content\\ module');
to select the element withid="content module"
.To target the element in CSS, you could escape it like this: