HTML DOM setAttributeNode() 方法
htmlweb developmentfront end technology更新于 2025/8/28 9:48:17
DOM setAttributeNode() 方法将其参数中指定的属性设置为 HTML 文档中的指定元素,并将该值作为 Attr Node 对象返回。
语法
以下是语法 −
node.setAttributeNode(attributeNode);
示例
让我们看一个 setAttributeNode() 方法的示例 −
<!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>
<h1>DOM setAttributeNode() method Demo</h1>
<p>Hi! I'm a para element in HTML with some random text</p>
<button onclick="set()" class="btn">Set Attribute</button>
<script>
function set() {
var p=document.querySelector("p");
var attr=document.createAttribute("style");
attr.value="color:#db133a;font-size:1.2rem;";
p.setAttributeNode(attr);
}
</script>
</body>
</html>
输出
这将产生以下输出 −
_method.jpg)
点击“设置属性”按钮为<p>元素设置样式属性。
_method_ex.jpg)
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

