如何在JavaScript中创建和删除属性节点?

时间:2018-12-21 08:10:18

标签: javascript html

我们如何在不使用jquery的情况下使用javascript创建和删除属性节点 createAttribute,removeAttribute

1 个答案:

答案 0 :(得分:0)

function myFunction() {
  var h1=document.getElementById("ik");
  var att = document.createAttribute("class");
  att.value = "democlass";
  h1.setAttributeNode(att);
}
function myFunction1() {
  var h1=document.getElementById("ik");
  var att = h1.getAttributeNode("class");
  h1.removeAttributeNode(att);
}
.democlass {
  color: red;
}
<!DOCTYPE html>
<html>
<body>

<h1 id="ik">Hello World</h1>

<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>

<button onclick="myFunction()">Try it</button>
<button onclick="myFunction1()">Try it</button>
</body>
</html>