jquery IDs with spaces

2019-01-02 20:32发布

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.

标签: jquery
11条回答
宁负流年不负卿
2楼-- · 2019-01-02 20:51

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>

查看更多
查无此人
3楼-- · 2019-01-02 20:52

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

var element = document.getElementById('content Module');
$(element) ... ;
查看更多
心情的温度
4楼-- · 2019-01-02 20:54

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

查看更多
余生请多指教
5楼-- · 2019-01-02 20:54

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"

查看更多
步步皆殇っ
6楼-- · 2019-01-02 20:55

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

查看更多
登录 后发表回答