js获取表单元素对象时采用多种获取方式完整代码
时间: 2023-11-25 19:06:18 浏览: 37
好的,以下是获取表单元素对象的多种方式的完整代码:
HTML 代码:
```
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="age">年龄:</label>
<input type="text" id="age" name="age">
<br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email">
</form>
```
JavaScript 代码:
```js
// 通过 ID 获取元素对象
const nameInput = document.getElementById('name');
const ageInput = document.getElementById('age');
const emailInput = document.getElementById('email');
// 通过 name 属性获取元素对象
const nameInputByName = document.getElementsByName('name')[0];
const ageInputByName = document.getElementsByName('age')[0];
const emailInputByName = document.getElementsByName('email')[0];
// 通过标签名和索引获取元素对象
const nameInputByTag = document.getElementsByTagName('input')[0];
const ageInputByTag = document.getElementsByTagName('input')[1];
const emailInputByTag = document.getElementsByTagName('input')[2];
// 通过类名和索引获取元素对象
const nameInputByClass = document.getElementsByClassName('name')[0];
const ageInputByClass = document.getElementsByClassName('age')[0];
const emailInputByClass = document.getElementsByClassName('email')[0];
// 通过 CSS 选择器获取元素对象
const nameInputBySelector = document.querySelector('#name');
const ageInputBySelector = document.querySelector('#age');
const emailInputBySelector = document.querySelector('#email');
```
需要注意的是,除了通过 ID 获取元素对象外,其他方式都返回的是一个类数组对象,需要使用索引访问具体的元素对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)