原生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');