1.getElementById():返回对拥有指定 id 的第一个对象的引用;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var a = document.getElementById("name").value;
var b = document.getElementById("password").value;
console.log(a);//获取id=name输入框中的字符串
console.log(b);//获取id=password输入框中的字符串
</script>
<input id="name" placeholder="请输入用户名" />
<input id="password" type="password" placeholder="请输入密码" />
</body>
</html>
2.getElementByClassName():返回对拥有指定 class 的第一个对象的引用;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var a = document.getElementById("name").value;
var b = document.getElementById("password").value;
console.log(a);//获取class=name输入框中的字符串
console.log(b);//获取class=password输入框中的字符串
</script>
<input class="name" placeholder="请输入用户名" />
<input class="password" type="password" placeholder="请输入密码" />
</body>
</html>
3.getElementsByName():返回带有指定名称的对象集合,这个可以获取单选框或复选框中的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var c= document.getElementsByName("sex");
for(var i=0;i<c.length;i++){
console.log(c[i]);//获取name=sex中的元素
}
var d= document.getElementsByName("happy");
for var i=0;i<c.length;i++){
console.log(d[i]);//获取name=happy中的元素
}
</script>
<input type="radio" name="sex" value="0"/>男<input type="radio" name="sex" value="1"/>女
<input type="checkbox" name="happy" value="0"/>篮球<input type="checkbox" name="happy" value="1"/>足球<input type="checkbox" name="happy" value="2"/>网球
</body>
</html>
4.getElementsByTagName():返回带有指定标签名的对象集合
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var string=getElementsByTagName("input");
for(var i=0;i<string.length;i++){
console.log(string[i]);//获取input标签中的元素
}
</script>
<input id="name" placeholder="请输入用户名" />
<input id="password" type="password" placeholder="请输入密码" />
</body>
</html>