Test if a browser supports a CSS selector

前端 未结 4 814
忘掉有多难
忘掉有多难 2020-12-15 09:55

Really simple: how do I most accurately test if a browser has support for a certain CSS selector?

I currently have some CSS code that makes the page a little more in

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 10:18

    A shorter way to do it would be to simply try the query selector, if it produces an error, return false, else true, like this:

    function testSelector(selector) {
      document.querySelector('*');  //checks if querySelector is implemented and raises an error if not
      try {document.querySelector(selector)} catch (e) {return false}
      return true;
    }
    

    I checked it on IE9 Windows and Chrome Mac (V43.0.2357.130), Win(V39.0.2171.95m), FireFox Win (V38.0.5), and it works fine with testSelector("form:invalid"), which is not implemented by IE9, but by everybody else.

提交回复
热议问题