<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h2 class="example">你很懒</h2>
<p>点击按钮为 class="example" (索引为 0) 的第一个元素设置背景颜色。</p>
<button onclick="mFunction()">点我</button>
<script>
function mFunction()
{
var x = document.querySelectorAll(".example");
x[0].style.backgroundColor = "blue";
}
</script>
</body>
</html>
querySelectorAll方法
使用function mFunction() {
var x = document.querySelectorAll(".example");
x[0].style.backgroundColor = "blue";
}
声明一个函数来使用它
x[0].style.backgroundColor = "blue";颜色为蓝色
把blue改成别的颜色就可以了
下面是输出的页面
点击,点我后颜色就会变成蓝的了