saber酱的抱枕

Fly me to the moon

02/9
16:19
学习

封装document.querySelector和document.querySelectorAll方法

JavaScript原生的document.querySelector和document.querySelectorAll方法很好用,不过依旧摆脱不了原生方法名太长的麻烦。所以我们可以封装下,如:

function $(selector) {
  return document.querySelector(selector)
}

function $$(selector) {
  return Array.prototype.slice.call(document.querySelectorAll(selector))
}

这里用了$、$$作为方法名,分别对document.querySelector方法和document.querySelectorAll方法进行封装。

$方法返回单个元素(第一个符合的元素),$$以数组形式返回所有符合的元素(即使符合的元素只有一个)。

这样我们就可以方便的使用封装的方法来选择DOM元素了:

$("#div .class img")
$$("#div .class img")

不过如果$、$$的定义冲突了可能会出问题,所以如果页面上引用jQuery了的话,可以换个方法名。

ps:至于为什么方法名要用$和$$呢,并不是模仿jQuery,而是模仿chrome(至于chrome是不是模仿jQuery的方法名那我就不清楚了)。

chrome浏览器控制台里内置了封装好的$、$$方法,可以直接使用。(当然,如果$、$$的定义被页面上的代码覆盖了就不行了)

如图:

封装document.querySelector和document.querySelectorAll方法

封装document.querySelector和document.querySelectorAll方法

封装document.querySelector和document.querySelectorAll方法