x
 
<!DOCTYPE html>
<html>
<style>
.democlass {color: red;}
</style>
<body>
<h1>Document 对象</h1>
<h2>createAttribute() 和 setAttributeNode() 方法</h2>
<p>创建 style 属性,为 h1 元素添加红色。</p>
<script>
// 创建 class 属性:
const att = document.createAttribute("style");
// 设置 class 属性的值:
att.value = "color:red";
// 在第一个 h1 中添加 class 属性:
const h1 = document.getElementsByTagName("h1")[0];
h1.setAttributeNode(att);
</script>
</body>
</html>