试了getElementsByName和getElementsByTagName都不行,只有getElementById可以,比如下面的例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
function red() {
var colour=document.getElementsByTagName("div");
colour.style.color="red";
}
</script>
</head>
<body>
<div>慕课网</div>
<br/>
<input type="button" value='更改颜色' onclick="red()">
</body>
</html> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
为什么不能通过getElementsTagName的方式改变文本的颜色?-PHP中文网问答-为什么不能通过getElementsTagName的方式改变文本的颜色?-PHP中文网问答
围观一下哦,学习一下。
getElementsByTagName获取的是数组。数组不能直接用style属性来设置的,用colour[0].style.color="red";可以实现
getElementsByName和getElementsByTagName获取的是一个由dom元素组成的数组。数组是无法直接用style属性来设置的,得先循环遍历这个数组,一项项取得dom元素再赋予style属性