Ood
Ood

Reputation: 1805

Check if the browser supports document.querySelectorAll in JavaScript

Now although most modern browser support document.querySelectorAll(), you may run into problems with older versions of Internet Explorer. The obvious way of checking if the browser supports a function would be:

if(document.querySelectorAll){
    //some random code
}

But from what I understand some browsers like (IE8) don't support certain properties, like 'body *'. Is there a better way to check if document.querySelectorAll('body *') will actually work?

Upvotes: 3

Views: 2673

Answers (3)

user5490177
user5490177

Reputation:

Check browser supports or not , without try-catch :

function QuerySelectors() {
  return (document['querySelector']&&document['querySelectorAll'])!=null;
}

or

function QuerySelectors(){
  return typeof(document['querySelector'])=='function'&&typeof(document['querySelectorAll'])=='function';
}

Read more > Reference

Upvotes: 4

plalx
plalx

Reputation: 43728

document.querySelectorAll will thrown on any unsupported selector so you can simply use a try-catch block.

Upvotes: 5

Adrian Preuss
Adrian Preuss

Reputation: 3113

Use typeof to check it:

 if(typeof(document.querySelectorAll) != 'undefined'){
      //some random code
 }

Upvotes: -2

Related Questions