ตัวอย่าง
หากต้องการตรวจสอบว่าองค์ประกอบถูกซ่อนอยู่หรือไม่ ให้ใช้ window.getComputedStyle() ตรวจสอบค่า display ว่าเป็น none หรือไม่
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.hiddenDiv {
width: 100%;
padding: 20px;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display: none;
font-size: 20px;
}
.showBtn {
border: none;
padding: 15px;
font-size: 18px;
background-color: rgb(86, 25, 155);
color: white;
}
</style>
</head>
<body>
<h1>ค้นหาองค์ประกอบที่ซ่อนด้วย JavaScript</h1>
<h2>คลิกปุ่มด้านล่างเพื่อแสดงองค์ประกอบที่ซ่อน</h2>
<button class="showBtn">แสดงองค์ประกอบ</button>
<div class="hiddenDiv"> นี่คือองค์ประกอบ DIV </div>
<script>
document.querySelector(".showBtn").addEventListener("click", showHidden);
function showHidden() {
var x = document.querySelector(".hiddenDiv");
if (window.getComputedStyle(x).display === "none") {
x.style.display = "block";
}
}
</script>
</body>
</html>
ผลลัพธ์
โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้:

เมื่อคลิกปุ่ม “แสดงองค์ประกอบ”:
