Skip to content Skip to sidebar Skip to footer

Test If A Browser Supports A CSS Selector

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 interactive by us

Solution 1:

You could use querySelector:

function testSelector(selector, node){
  var scope = document.createElement("div");
  scope.appendChild(node);

  try {
    return scope.querySelector(selector) !== null;
  } catch(e) { return false; }
}

You can test it like this:

var node = document.createElement("input");
node.type = 'checkbox';
node.checked = 'checked';

testSelector("input:checked", node); // === true

See this other question for more info on querySelector.


Solution 2:

From some research I was able to find various websites that can test your browser to see the support.

This website is helpful to find what supports what but does not test your current browser.

This website will test your browser and if you don't want to use modernizr you can learn from their script.

This last website seems to do a great job and is very accurate of the support. I also am pretty sure I found the script that is doing this so like I said you can learn from how other website are doing this.

To figure how they are making this work you will need to understand how their scripts are working. The bottom three seem to be the most critical to the function.

<script src="utopia.js"></script>
<script src="supports.js"></script>
<script src="csstest.js"></script>
<script src="tests.js"></script>

These are just some options that I found and it is up to your needs. Best of luck and hopefully this has been helpful.


Solution 3:

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.


Post a Comment for "Test If A Browser Supports A CSS Selector"