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

如何使用getElementsByClassName仅选取input标签并获取其值?

只获取指定类名的input元素的值

你可以通过以下两种方式精准获取带example类名的input元素的值:

方法一:使用CSS选择器直接定位

利用document.querySelectorAll()或document.querySelector(),通过input.example选择器直接选中所有(或单个)带example类的input元素,避免混入其他标签元素:

获取所有符合条件的input元素并操作

// 获取所有带example类的input元素
const inputElements = document.querySelectorAll("input.example");

// 遍历所有input元素,获取或修改值
inputElements.forEach(input => {
  console.log(input.value); // 输出input1、input2
  // input.value = "新值"; // 可修改值
});

获取单个符合条件的input元素

如果只需要第一个input元素:

const firstInput = document.querySelector("input.example");
firstInput.value = "Hello World!"; // 直接修改第一个input的值

方法二:过滤类选择器的结果

如果坚持使用getElementsByClassName,可以将返回的HTMLCollection转为数组后,过滤出标签为INPUT的元素:

const collection = document.getElementsByClassName("example");
// 转为数组并过滤出input元素
const inputElements = Array.from(collection).filter(el => el.tagName === "INPUT");

// 操作第一个input元素
inputElements[0].value = "Hello World!";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:07:33