代码示例:(标识:jsck_element_setattributenode)
<!DOCTYPE html>
<html>
<style>
.democlass {
  color: red;
}
</style>

<body>

<h1>Element 对象</h1>

<h2>setAttributeNode() 方法</h2>

<p>点击“更改”,设置第一个标题的 class 属性节点。</p>

<button onclick="myFunction()">更改</button>

<script>
function myFunction() {
  const attr = document.createAttribute("class");
  attr.value = "democlass";
  const element = document.getElementsByTagName("H1")[0];
  element.setAttributeNode(attr); 
}
</script>

</body>
</html>
运行结果: