Check if the browser supports document.querySelectorAll in JavaScript

ⅰ亾dé卋堺 提交于 2019-12-04 04:02:20

问题


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?


回答1:


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




回答2:


Test browser support 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




回答3:


Use typeof to check it:

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


来源:https://stackoverflow.com/questions/22286844/check-if-the-browser-supports-document-queryselectorall-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!