nickf
nickf

Reputation: 545995

Detecting CSS capabilities with Javascript

Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

input[type='text'] { }

Upvotes: 5

Views: 274

Answers (3)

Tomalak
Tomalak

Reputation: 338138

document.querySelectorAll("input[type='text']")

But that fails for older browsers, naturally.

Other than that, you could just use the style property to check if a certain CSS property has been applied or not.

input[type='text'] {
  background-repeat: no-repeat; /* or any other irrelevant, non-default value */
}

and

if (myInputElem.style.backgroundRepeat == "no-repeat") {
  // selector is supported
}

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179046

This is a bit speculative as I haven't tested it out, but I believe it would be possible via JS to add a style element followed by an element that it has an effect on, and then test the values:

Speculative untested code, may or may not work (jQuery used for brevity):

$('<style type="text/css" id="foo">input[type="text"]{ width: 10px; }</style>').appendTo('head');
$('<input type="text" id="bar">').appendTo('body');
if ($('#bar').width() == 10)
{
  //attr selector supported
}
$('#foo, #bar').remove();

Upvotes: 3

Mark Robinson
Mark Robinson

Reputation: 13278

Modernizr is designed to detect browser features and may well be able to help in this instance. http://www.modernizr.com/

Upvotes: 5

Related Questions