Adding HTML5 query selector to browsers dont't support it

寵の児 提交于 2019-12-04 12:17:47

You can simply use the original Sizzle engine which jQuery uses (written by John Resig, author of jQuery).

Here's Sizzle's own description:

A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library.


If you want to be sure that you don't use Sizzle if querySelectorAll is natively supported (even though Sizzle will always use querySelectorAll when available), use this:

if ( ! document.querySelectorAll ) document.querySelectorAll = Sizzle;

It is usually a bad idea to use complex selectors to find elements as it tightly binds the script functionality to the layout and presentation of the document. A simpler strategy should be employed, such as using ids, classes or grouping elements in the document.

If you do that, then analyse your requirements, you may find you only need a couple of simple selectors. In that case, the standard DOM methods of accessing elements may do 90% of the job and you just need to add a bit of filtering. e.g. '#id' is just getElementById (which is what jQuery/Sizzle actaully uses for that selector), and '.myClass a' can use a fairly simple getElementsByClassname function (most browsers have one built in) with a filter for A elements.

Of course such functions could first test for qSA support and use it if available.

Note also that there are a number of live document collections already avaialbe that can be very efficient to use, and also the early DOM collections (such as getElementsByTagName) were live too. I'm pretty sure the qSA returns static collections because that's what javascript libraries with selectors had been doing.

Anyhow, food for thought.

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