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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With