Check if CSS selector is really selected

I have a field for the user to enter a CSS selector, and I want to check if it is valid (according to the css3 specification ). I tried using the expressions from the css3 specification , as suggested in https://stackoverflow.com/a/3/412743/169 , but it didn’t work - the regular expression I built just didn't match the valid selectors. At the moment, I just:

try {
     document.querySelector(selector);
} catch (e) {
     // handle bad input
}

But this does not seem like a good solution. The querySelector function is for retrieving elements, and checking the selector is just a side effect. In addition, it does not provide any information about what is wrong with the selector.

I am looking for something like document.validateSelectoror a library for parsing CSS selectors.

+5
source share
3 answers

You can use the library to check if the selector is valid, and possibly get more information from the parsing. Check out the CSS selector selector .

+1
source

The problem with the original idea is that it will look for the entire document. Slow!!! But if we are looking for an empty lightweight element that is not even attached to the DOM, everything should be fine!

The self-executing transfer function ensures that there is only one hidden one dummythat cannot be dispensed with.

const qs = s => document.createDocumentFragment().querySelector(s)

const isSelectorValid = selector => {
  try { qs(selector) } 
  catch (e) { return false }
  return true
}


console.log(isSelectorValid("a#x#y"), isSelectorValid("a?+"))
Run codeHide result

+6

, , document.querySelector() null. , present document.querySelector(), it will return the item.

This is where JSFiddle works .

-1
source

Source: https://habr.com/ru/post/1624737/


All Articles