<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 500px;
height: 50px;
}
.anotherClass {
background-color: lightblue;
}
.thirdClass {
text-align: center;
font-size: 25px;
color: black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>点击按钮显示div的第一个类(index 0)的类名。</p>
<div id="myDIV" class="mystyle anotherClass thirdClass">
我是一个 DIV 元素 with three classes
</div>
<button onclick="myFunction()">试一试</button>
<p><strong>注意:</strong> Internet Explorer 9 及更早版本不支持 classList 属性。</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myDIV").classList.item(0);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>