You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在纯现代JavaScript中简洁高效地选择元素?

太懂这种心情了!jQuery的$('mySelector')用惯了之后,再写冗长的document.querySelectorAll简直浑身难受,而且原生返回的NodeList还得额外处理单个/多个元素的情况,确实麻烦。我来分享几个纯现代JS的方案,完美复刻jQuery选择器的爽感,还不用加载整个库:

1. 先优化基础的$选择器函数,自动处理单个/多个元素

先把原生选择器封装成更智能的函数,解决“每次都要索引元素或判断长度”的问题:

const $ = (selector, context = document) => {
  const elements = context.querySelectorAll(selector);
  // 智能返回:匹配到单个元素直接返回DOM节点,多个则返回NodeList
  return elements.length === 1 ? elements[0] : elements;
};

这个函数的优势:

  • 写法和jQuery完全一致,比如$('#main')直接拿到单个DOM元素,不用再写[0];
  • 支持上下文选择,比如在容器内查找元素:$('.item', $('.card-container')),省去嵌套调用的麻烦;
  • 匹配多个元素时返回的NodeList,在现代JS里已经原生支持forEach,直接遍历即可,不用手动转数组。

2. 扩展常用方法,实现jQuery式链式调用

如果还想要$('.box').addClass('active').on('click', ...)这种链式操作体验,可以给DOM元素和NodeList的原型扩展常用方法:

// 给单个DOM元素扩展方法
Object.defineProperties(Element.prototype, {
  addClass: {
    value(className) {
      this.classList.add(className);
      return this; // 返回自身,支持链式调用
    }
  },
  removeClass: {
    value(className) {
      this.classList.remove(className);
      return this;
    }
  },
  on: {
    value(eventType, handler) {
      this.addEventListener(eventType, handler);
      return this;
    }
  },
  text: {
    value(content) {
      if (typeof content !== 'undefined') {
        this.textContent = content;
        return this;
      }
      return this.textContent;
    }
  }
});

// 给NodeList扩展批量操作方法
Object.defineProperties(NodeList.prototype, {
  addClass: {
    value(className) {
      this.forEach(el => el.classList.add(className));
      return this;
    }
  },
  removeClass: {
    value(className) {
      this.forEach(el => el.classList.remove(className));
      return this;
    }
  },
  on: {
    value(eventType, handler) {
      this.forEach(el => el.addEventListener(eventType, handler));
      return this;
    }
  }
});

现在你就能像用jQuery一样操作元素了:

  • 单个元素操作:$('#header').addClass('sticky').text('Hello World').on('click', () => console.log('点击了头部'))
  • 批量元素操作:$('.nav-link').addClass('active').on('mouseover', (e) => e.target.style.color = '#2c3e50')

3. 额外小技巧:NodeList转数组

如果需要用到数组的filter、map等方法,现代JS里可以直接用扩展运算符或Array.from快速转换:

// 把NodeList转成数组
const itemArray = [...$('.list-item')];
// 或者
const itemArray = Array.from($('.list-item'));

这些方案完全基于现代原生JS,没有任何外部依赖,既保留了jQuery选择器的简洁性,又解决了原生方法的冗余问题,用起来几乎和jQuery一模一样。

内容的提问来源于stack exchange,提问作者temporary_user_name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:58:26