这是我刚刚创建的一个函数,用于处理 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 );