document.getElementById()

本文详细解析了JavaScript中的getElementById方法,包括其语法、参数说明及返回值。通过两个实例展示了如何使用此方法选择页面上的元素并修改其样式和内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

句法:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值