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

如何获取jQuery查询的首个结果元素?含变量中jQuery执行与DOM获取

嘿,这两个都是jQuery开发里高频碰到的场景,我来给你拆解清楚每种情况的解法:

1. 给定一个jQuery选择器,如何获取它的首个结果元素?

你有两种核心思路,取决于你需要的是jQuery对象还是原生DOM元素:

  • 要是想继续链式调用jQuery方法(比如加样式、绑定事件),用.first()或.eq(0)返回jQuery对象:
    // 两种写法效果一致,都返回首个匹配的jQuery对象
    const $firstJQueryElem = $('.target-class').first();
    const $firstJQueryElem = $('.target-class').eq(0);
    
    // 可以直接链式调用jQuery方法
    $firstJQueryElem.addClass('active');
    
  • 如果需要原生DOM元素本身(要用原生JS API操作),用数组下标[0]或者.get(0):
    const firstDomElem = $('.target-class')[0];
    // 或者等价写法
    const firstDomElem = $('.target-class').get(0);
    
    // 用原生JS方法操作
    if (firstDomElem) {
      firstDomElem.classList.add('active');
    }
    

小提醒:如果选择器没匹配到任何元素,[0]或.get(0)会返回undefined,最好先判断$('.target-class').length > 0再操作。

2. 若变量中存储了jQuery对象,如何执行查询并获取首个匹配的DOM元素本身(若存在)?

假设你的变量是$container(已经是一个jQuery对象),分两种查询场景:

  • 要查询这个对象的子元素/后代元素:用.find()缩小查询范围,再取原生DOM元素:
    const $container = $('#my-page-container');
    // 在容器内查询符合条件的元素,取首个DOM元素
    const firstChildDom = $container.find('.child-selector').get(0);
    
  • 要从已有的jQuery元素集合里筛选(比如从一堆列表项里找带active类的):用.filter():
    const $allListItems = $('.list-item');
    // 从已有的列表项里筛选出带.active的首个DOM元素
    const firstActiveDom = $allListItems.filter('.active')[0];
    

同样,为了避免空值报错,建议先判断匹配结果的长度:

const $matches = $container.find('.child-selector');
if ($matches.length) {
  const targetDom = $matches.get(0);
  // 执行你的操作
}

内容的提问来源于stack exchange,提问作者g.pickardou

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:47:28