Phương thức setAttributeNode() trong HTML DOM thiết lập một thuộc tính được chỉ định trong tham số cho một phần tử cụ thể trong tài liệu HTML và trả về giá trị dưới dạng đối tượng Attr Node.
Cú pháp
node.setAttributeNode(attributeNode);
Ví dụ
Ví dụ sử dụng phương thức 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>Demo phương thức setAttributeNode() DOM</h1>
<p>Chào! Tôi là một phần tử p trong HTML với một số văn bản ngẫu nhiên</p>
<button onclick="set()" class="btn">Thiết lập thuộc tính</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>
Kết quả
Nhấn nút Thiết lập thuộc tính để thiết lập thuộc tính style cho phần tử <p>.