原生JS替代jQuery的各种方法汇总
你也许不需要 jQuery (You (Might) Don't Need jQuery)
Query 选择器
常用的 class、id、属性 选择器都可以使用 document.querySelector
或 document.querySelectorAll
替代。区别是
document.querySelector
返回第一个匹配的 Elementdocument.querySelectorAll
返回所有匹配的 Element 组成的 NodeList。它可以通过[].slice.call()
把它转成 Array- 如果匹配不到任何 Element,jQuery 返回空数组
[]
,但document.querySelector
返回null
,注意空指针异常。当找不到时,也可以使用||
设置默认的值,如document.querySelectorAll(selector) || []
注意:
document.querySelector
和document.querySelectorAll
性能很差。如果想提高性能,尽量使用document.getElementById
、document.getElementsByClassName
或document.getElementsByTagName
。
1.0 选择器查询
// jQuery
$('selector');
// Native
document.querySelectorAll('selector');