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

技术咨询:如何将$('input[type=text]')转换为原生JavaScript?

将jQuery选择器$('input[type=text]')转为原生JavaScript代码

要实现和这段jQuery代码相同的元素选择效果,原生JavaScript有几种对应写法:

  • 选中所有匹配的<input type="text">元素(对应jQuery返回的多元素集合):
    使用document.querySelectorAll('input[type=text]'),它会返回一个NodeList对象,包含所有符合选择器的元素,和jQuery对象的行为最接近。如果需要对这个集合使用数组方法(比如forEach、map),可以把它转为数组:

    // 转为数组的两种方式
    const textInputs = Array.from(document.querySelectorAll('input[type=text]'));
    // 或者
    const textInputs = [...document.querySelectorAll('input[type=text]')];
    
  • 仅选中第一个匹配的<input type="text">元素(对应$('input[type=text]').first()):
    使用document.querySelector('input[type=text]'),它会直接返回匹配到的第一个元素,没有匹配到则返回null。

需要注意的是,原生的NodeList和jQuery对象不同,不能直接调用jQuery的方法(比如val()、addClass()),需要用原生DOM API来操作元素,比如获取值用element.value,添加类用element.classList.add('className')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:30:51