句法:
var element = document .getElementById(id);
参量:
id:要定位的元素的id。id是区分大小写的字符串,且在文档中是唯一的。只有一个元素可以具有任何给定的id。
返回值
返回对拥有指定 ID 的第一个对象的引用
- 如果没有指定 ID 的元素返回 null
- 如果存在多个指定 ID 的元素则返回第一个
例1
HTML代码:
<html>
<head>
<title>getElementById example</title>
</head>
<body>
<p id="para">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>
JavaScript代码:
function changeColor(newColor) {
var elem = document.getElementById('para');
elem.style.color = newColor;
}
结果:
例2
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p id="demo">单击按钮来改变这一段中的文本。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
document.getElementById("demo").innerHTML="Hello World";
};
</script>
</body>
</html>
结果
转载:
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById
https://www.runoob.com/jsref/met-document-getelementbyid.html