getElementById():
返回对拥有指定 id 的第一个对象的引用。 具有唯一性,因为一个页面的id唯一,不允许重复
<div id="1111">
<span>郑州大学</span><i>河南工业大学</i>
<p class="a">123</p><p class="a">abc</p>
<input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/>
</div>
<script>
var element = document.getElementById("1111");
console.log(element);
</script>
getElementsByName():
返回带有指定名称的对象集合。
示例:
var elements = document.getElementsByName("hobby");
for (var i = 0;i<elements.length;i++) {
console.log(elements[i]);
}
getElementsByTagName():
返回带有指定标签名的对象集合。
示例:
var elements = document.getElementsByTagName("p");
for (var i = 0;i<elements.length;i++) {
console.log(elements[i]);
}
getElementsByClassName:
返回带有指定class的对象集合
var elements = document.getElementsByClassName("a");
for (var i in elements) {
console.log(elements[i]);
}
整体代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="1111">
<span>郑州大学</span><i>河南工业大学</i>
<p class="a">123</p><p class="a">abc</p>
<input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/><input type="checkbox" name="hobby"/>
</div>
<script>
var element = document.getElementById("1111");
console.log(element);
var elements = document.getElementsByClassName("a");
for (var i in elements) {
console.log(elements[i]);
}
var elements = document.getElementsByName("hobby");
for (var i = 0;i<elements.length;i++) {
console.log(elements[i]);
}
var elements = document.getElementsByTagName("p");
for (var i = 0;i<elements.length;i++) {
console.log(elements[i]);
}
</script>
</body>
</html>