javascript代码实例教程-querySelector和querySelectorAll

发布时间:2019-02-24 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-querySelector和querySelectorAll脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。 jQuery开发者如此的青睐和它强大的选择器有很大关系,比起笨重的document.getElementById、document.getElementByName… ,查找元素很方便,其实W3C中提供了querySelector和querySelectorAll查询接口已经实现了类似功能。

 

定义

其实这两个方法看名字就能明白什么意思不过还是引用一下W3C的解释

 

querySelector:return the First matching Element node wIThin the node’s suBTrees. If there is no such node, the method must return null .(返回指定元素节点的子树中匹配选择器的集合中的第一个元素,如果没有匹配返回null)

 

querySelectorAll:return a nodelist containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList. (按文档顺序返回指定元素节点的子树中匹配选择器的元素集合,如果没有匹配返回空集合)

 

从定义可以看到Document和Element都实现了NodeSelector接口。即这三种类型的元素都拥有者两个方法。querySelector和querySelectorAll的参数是CSS选择器字符串。区别在于querySelector返回的是一个第一个匹配元素,querySelectorAll返回的一个所有匹配元素集合(NodeList)。

 

用法

如果使用过jquery或者了解CSS,这两个方法使用很简单,传入选择器即可

 

 

<p id="test">

        <p class="diaLOG">

            <p>

                123</p>

            <span>456</span>

            <p>

                789</p>

            <p class="text">

                452</p>

        </p>

    </p>

 

VAR test=document.querySelector(&#39;#test');

        var subDivs = test.querySelectorAll('p');

        var text = document.querySelectorAll('p[class=text]');

 

 

缺陷及解决办法

确实很好用,但是浏览器对Element.querySelector和Element.querySelectorAll的实现有错误,看个例子

 

<p id="test">

        <p>

            <span>123</span>

        </p>

    </p>

var test=document.querySelector('#test');

        var span = test.querySelectorAll('p span');

按照我们的理解span因该是搜索test内部祖先元素为p的span元素,但是其祖先必须在test内部,而不能包括test本身甚至test的父元素,所以应该返回空基赫才对,但是浏览器会返回

 

 

 

大神Andrew Dupont提出了一种方法修复这个bug,被广泛应用到各个框架中,在selector前面指定调用元素的id,限制匹配范围。在jQuery中大概是这么个意思

 

 

var span, selector = 'p span',context=document.querySelector('#test');

 

        var oldContext = context,

        oldId = context.getAttribute('id'),

        newId = oldId || '__sizzle__';

        try {

            span= context.querySelectorAll('#'+newId+' '+selector);

        } catch (e) {

            

        } finally {

            if (!oldId) {

                oldContext.removeAttribute('id');

            }

        }

 

这样做其实是给搜索加了一层id的限制,巧妙的利用了这个bug,得到正确结果

 

 

 

浏览器兼容性

虽然有些问题,但瑕不掩瑜,这么好用的两个方法咋没火呢?浏览器兼容性。。。其实比起一些HTML5和CSS3的特性来说这两个方法还没那么让人绝望,因为IE8都已经支持了,其它各个主力主流浏览器自然是实现了。

 

IE8+

 

Firefox

 

Chrome

 

Safari

 

opera

 

AndROId

 

所以骚年们如果你是针对mobile web优化,不要引用jQuery了,直接使用这两个方法吧

 

觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的javascript代码实例教程-querySelector和querySelectorAll全部内容,希望文章能够帮你解决javascript代码实例教程-querySelector和querySelectorAll所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。