Lấy giá trị thuộc tính đối tượng style trong JavaScript

Trình soạn thảo - Lấy giá trị thuộc tính đối tượng style trong JavaScript

Kết quả - Lấy giá trị thuộc tính đối tượng style trong JavaScript

Tự code rồi chạy thử... Chạy Thử
<!DOCTYPE html>
<html>
<head>
<title>Lấy giá trị thuộc tính đối tượng style trong JavaScript</title>
</head>
<body>

<h1>Lấy giá trị thuộc tính đối tượng style trong JavaScript</h1>
<p>Đối tượng style trong JavaScript dùng để css cho một phần tử HTML bằng cách khởi tạo thuộc tính và gán giá trị cho thuộc tính đó, ở ví dụ này mình tạo css xong sẽ lấy thông tin css đã tạo:</p>

<div id="divid">Thẻ DIV cần CSS</div>
<p>Click vào nút THÊM CSS để css cho phần tử HTML, Click vào nút LẤY CSS để lấy giá trị </p>
<button onclick="themCss()">THÊM CSS</button>
<button onclick="layCss()">LẤY CSS</button>
<div id="ketqua"></div>
<script>
function themCss() {
  document.getElementById("divid").style.backgroundColor = "black";
  document.getElementById("divid").style.color = "#fff";
  document.getElementById("divid").style.textAlign = "center";
  document.getElementById("divid").style.lineHeight = "50px";
  document.getElementById("divid").style.border = "3px solid red";
  document.getElementById("divid").style.fontWeight = "bold";
  document.getElementById("divid").style.fontSize = "20px";
  document.getElementById("divid").style.textTransform = "uppercase";
}
function layCss() {
  const divid = document.getElementById('divid');
  const ketqua = document.getElementById('ketqua');
  const cssduoclay = window.getComputedStyle(divid);
  const node = document.createElement("p");
  const textnode = document.createTextNode("backgroundColor: "+cssduoclay.backgroundColor);
  node.appendChild(textnode);
  document.getElementById("ketqua").appendChild(node);
  const nodehai = document.createElement("p");
  const textnodehai = document.createTextNode("color: "+cssduoclay.color);
  nodehai.appendChild(textnodehai);
  document.getElementById("ketqua").appendChild(nodehai);
  
}
</script>
</body>
</html>