Check if the browser supports document.querySelect

2019-02-26 03:33发布

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?

3条回答
何必那么认真
2楼-- · 2019-02-26 03:45

test Browser support or not , without try-catch

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

or

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

thanx : http://htmlgoodies.com/beyond/javascript/using-javascripts-css3-selectors.html

查看更多
做个烂人
3楼-- · 2019-02-26 03:45

Use typeof to check it:

 if(typeof(document.querySelectorAll) != 'undefined'){
      //some random code
 }
查看更多
小情绪 Triste *
4楼-- · 2019-02-26 03:55

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

查看更多
登录 后发表回答