首页 > 解决方案 > 选择器抛出 DOMException 但在控制台中工作 - Tailwind 类选择器

问题描述

我正在使用 Tailwind CSS 和 vanilla JS,我正在尝试通过内置选择器获取一些特定节点。问题:当浏览器执行的代码(捆绑在 Webpack 中)时,选择器被标记为无效,但我可以让它在 Web 控制台中工作。

代码抛出的 DOMException

这是一个可复制的样本;问题似乎在于w-2/4包含 a/所以我正在逃避它以使其像\\/. 采取任何想法来解决这个问题......

const prefix = '.';
const width = 'w-2/4';
const rounded = 'rounded';

const selector = prefix + width + prefix + rounded;
parsed = selector.replace('/', '\\\\/');

console.log(parsed);

const matches = document.querySelectorAll('.w-2\\/4.rounded');
console.log(matches);

const broken = document.querySelectorAll(parsed);
console.log(broken);
<h3 class="inline-block statlib-kpi-value text-2xl h-4 bg-blue-400 rounded w-2/4 "></h3>

由@biberman 回答,感谢他。

标签: javascripttailwind-css

解决方案


我认为问题在于这里有 4 个反斜杠parsed = selector.replace('/', '\\\\/');,应该只有两个 ...

工作示例:

const prefix = '.';
const width = 'w-2/4';
const rounded = 'rounded';

const selector = prefix + width + prefix + rounded;
parsed = selector.replace('/', '\\/');

console.log(parsed);

const matches = document.querySelectorAll('.w-2\\/4.rounded');
console.log(matches);

const broken = document.querySelectorAll(parsed);
console.log(broken);
<h3 class="inline-block statlib-kpi-value text-2xl h-4 bg-blue-400 rounded w-2/4 "></h3>


推荐阅读