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:43

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() );
}
查看更多
唯独是你
3楼-- · 2019-01-02 20:45

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

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

Note the double-backslash, which is required.

查看更多
大哥的爱人
4楼-- · 2019-01-02 20:45

This worked for me.

document.getElementById(escape('content Module'));
查看更多
公子世无双
5楼-- · 2019-01-02 20:45

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');

查看更多
唯独是你
6楼-- · 2019-01-02 20:49

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.

查看更多
旧时光的记忆
7楼-- · 2019-01-02 20:51

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>
查看更多
登录 后发表回答