getElementById
是JavaScript中的一个DOM方法,用于根据元素的
id
属性获取HTML文档中的元素。该方法接受一个字符串参数,即元素的
id
属性值,并返回具有该
id
属性值的元素。如果没有找到匹配的元素,则返回
null
。
以下是一个示例,演示如何使用
getElementById
获取页面中的元素:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用getElementById获取元素</title>
</head>
<body>
<h1 id="heading">这是页面标题</h1>
<p id="paragraph">这是一个段落</p>
<script>
// 获取元素并修改其文本内容
const headingElement = document.getElementById("heading");
headingElement.textContent = "这是新标题";
const paragraphElement = document.getElementById("paragraph");
paragraphElement.textContent = "这是新的文本内容";
</script>
</body>
</html>
在这个示例中,
<h1>
元素和
<p>
元素都有一个
id
属性,分别为
“heading”
和
“paragraph”
。在JavaScript代码中,通过
document.getElementById
方法获取这两个元素,并使用
textContent
属性来修改它们的文本内容。注意,
getElementById
方法只会返回具有指定
id
属性值的第一个元素,如果有多个元素具有相同的
id
属性值,则只会返回第一个匹配的元素。