我有一个供用户输入 CSS 选择器的字段,我想检查它是否有效(根据 css3 specification )。我尝试使用 css3 specification 中的表达式正如 another stackoverflow topic 中所建议的那样, 但它不起作用 - 我构建的正则表达式与有效的选择器不匹配。我现在所拥有的只是:
try {
document.querySelector(selector);
} catch (e) {
// handle bad input
}
但这似乎不是一个好的解决方案 - querySelector 函数是为获取元素而设计的,检查选择器只是一个副作用。此外,它不提供有关选择器问题的任何信息。
我正在寻找类似 document.validateSelector
或用于解析 CSS 选择器的库。
最佳答案
原始思路的问题是它会搜索整个文档。 慢 🤨 !
然而,搜索一个甚至没有附加到 DOM 的空轻量级元素是快速✌️!
const queryCheck = (s) => document.createDocumentFragment().querySelector(s)
const isSelectorValid = (selector) => {
try { queryCheck(selector) } catch { return false }
return true
}
console.assert(isSelectorValid('p > > > a') === false)
console.assert(isSelectorValid('p > a') === true)
console.log('Test passed')
以下版本使用虚拟片段外壳更高级一些:
const isSelectorValid = ((dummyElement) =>
(selector) => {
try { dummyElement.querySelector(selector) } catch { return false }
return true
})(document.createDocumentFragment())
console.assert(isSelectorValid('p > > > a') === false)
console.assert(isSelectorValid('p > a') === true)
console.log('Test passed')
关于javascript - 检查 CSS 选择器是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849001/