HTML DOM setAttributeNode() Method
DOM setAttributeNode()方法将在其参数中指定的属性设置为HTML文档中的指定元素,并将该值作为Attr节点对象返回。
句法
以下是语法-
1 | node.setAttributeNode(attributeNode); |
例
让我们看一个setAttributeNode()方法的例子-
现场演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!DOCTYPE html> <html> <head> <style> html{ height:100%; } body{ text-align:center; color:#fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height:100%; } .btn{ background:#0197F6; border:none; height:2rem; border-radius:2px; width:35%; margin:2rem auto; display:block; color:#fff; outline:none; cursor:pointer; } </style> </head> <body> DOM setAttributeNode() method Demo <p> Hi! I'm a para element in HTML with some random text </p> <button onclick="set()" class="btn">Set Attribute</button> function set() { var p=document.querySelector("p"); var attr=document.createAttribute("style"); attr.value="color:#db133a;font-size:1.2rem;"; p.setAttributeNode(attr); } </body> </html> |
输出量
这将产生以下输出-
单击"设置属性"按钮,将样式属性设置为
元件。