Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 using the :checked selector in CSS, but I want to create a fallback script that does the same thing with JavaScript, but only if the user's browser has no support for the :checked selector.

My question is, how do I most accurately test if the user's browser supports a certain CSS selector?

Here is the code I'd like to use it on:

HTML:

<label class="coolbox">
    <input type="checkbox"/>
    <span>I want to eat some caek.</span>
</label>

CSS:

.coolbox input {display:none;}
.coolbox span::before {
    content: "";
    display:inline-block;
    width:10px;
    height:10px;
    margin-right:5px;
    border:1px solid black;
}
.coolbox:hover span::before {border:1px solid #555;}
.coolbox:active span::before {border:1px solid #999;}

.coolbox span::before {background-color:#F77;}
.coolbox input:checked + span::before {background-color:#4A4;}

Demo

PS: I'd prefer not to just use conditional comments, because I'd like to follow the standard of detecting features instead of browsers.

like image 372
Joeytje50 Avatar asked Jan 13 '14 15:01

Joeytje50


1 Answers

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.

like image 179
Matt Avatar answered Oct 07 '22 17:10

Matt