使用ID为数字的querySelector

Ber*_*lue 76 javascript html5 css-selectors selectors-api

根据我的理解,HTML5规范允许您使用像这样的数字的ID.

<div id="1"></div>
<div id="2"></div>
Run Code Online (Sandbox Code Playgroud)

我可以使用getElementById但不能使用这些querySelector.如果我尝试执行以下操作,我会在控制台中获得SyntaxError:DOM Exception 12.

document.querySelector("#1")
Run Code Online (Sandbox Code Playgroud)

我只是好奇为什么querySelector当HTML5规范说这些有效时,使用数字作为ID不起作用.我试过多个浏览器.

Den*_*nis 90

它是有效的,但需要一些特殊处理.从这里:http://mathiasbynens.be/notes/css-escapes

领先的数字

如果标识符的第一个字符是数字,则需要根据其Unicode代码点对其进行转义.例如,字符1的代码点是U + 0031,因此您可以将其转义为\ 000031或\ 31.

基本上,要转义任何数字字符,只需在其前面添加\ 3并附加空格字符().是的Unicode!

所以你的代码最终会成为(CSS first,JS second):

#\31  {
    background: hotpink;
}

document.getElementById('1');
document.querySelector('#\\31 ');
Run Code Online (Sandbox Code Playgroud)

  • 在第一个字符后需要一个空格:`#\\ 31 0` - 你可以参考http://mothereffingcssescapes.com/ (5认同)

Nie*_*sol 70

因为虽然它们在HTML5规范中有效,但它们在CSS中无效,这就是"查询选择器 "的含义.

相反,你必须这样做:document.querySelector("[id='1']")这是非常啰嗦,考虑到你可以给它一个有意义的 ID像message1或什么;)

  • UUID可以以数字开头. (7认同)
  • 如果你有一个 id 列表,你可以使用 ``document.querySelectorAll(myIds.map(id =&gt; `[id="${id}"]`).join(', '))`` (2认同)

Gla*_*001 5

我需要一种自动化的方法。最近的更改意味着所使用的id值不再是简单的字母字符,而是包含数字和特殊字符。

我最终使用了CSS.escapehttps : //developer.mozilla.org/en-US/docs/Web/API/CSS/escape

console.log(CSS.escape('1'));
Run Code Online (Sandbox Code Playgroud)

首先,这是失败的情况:

const theId = "1";
document.querySelector(`#${theId}`);
const el = document.querySelector(`#${theId}`);
el.innerHTML = "After";
Run Code Online (Sandbox Code Playgroud)
<div id="1">Before</div>
Run Code Online (Sandbox Code Playgroud)

现在使用CSS.escape

const theId = "1";
const el = document.querySelector(`#${CSS.escape(theId)}`);
el.innerHTML = "After";
Run Code Online (Sandbox Code Playgroud)
<div id="1">Before</div>
Run Code Online (Sandbox Code Playgroud)

看看它如何正确更改为show After,表明选择器有效!


Per*_*Per 5

这是我刚刚创建的一个函数,用于处理 CSS 选择器中的前导数字 ID,它是 IE 安全的,因为 CSS.escape 不是。

在使用之前通过这个 cleanSelector 函数传递选择器:

var cleanSelector = function(selector){
    (selector.match(/(#[0-9][^\s:,]*)/g) || []).forEach(function(n){
        selector = selector.replace(n, '[id="' + n.replace("#", "") + '"]');
    });
    return selector;
};

var myselector = ".dog #980sada_as div span#aside:hover div.apple#05crab:nth-of-type(2), .ginger #2_green_div, div.cupcake #darwin p#23434-346365-53453";

var clean_myselector = cleanSelector(myselector);

// print to show difference
console.log(myselector);
console.log(clean_myselector);

//use the new selector like normal
var elems = document.querySelectorAll( clean_myselector ); 


Run Code Online (Sandbox Code Playgroud)