คุณสมบัติ HTML DOM innerHTML ส่งคืนและอนุญาตให้เราแก้ไข HTML ภายในขององค์ประกอบ HTML ด้านในคือเนื้อหา
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
1. ส่งคืน innerHTML
object.innerHTML
2. การตั้งค่า HTML ภายใน
object.innerHTML=”value”
ที่นี่ “คุณค่า ” หมายถึงเนื้อหาหรือองค์ประกอบ HTML ที่ซ้อนกัน
ตัวอย่าง
ให้เรามาดูตัวอย่างคุณสมบัติ innerHTML −
<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
}
.outer-box{
background-color:#347924;
width:200px;
height:200px;
padding:10px;
text-align:center;
font-weight:bold;
color:white;
margin:1rem auto;
}
.inner-box{
width:100px;
height:100px;
margin:3rem auto;
background-color:#8dce79;
}
.inner-circle{
width:100px;
height:100px;
border-radius:50%;
background-color:#8dce79;
margin:3rem auto;
}
</style>
</head>
<body>
<h1>innerHTML property Example</h1>
<div class="outer-box">
</div>
<button onclick="getsquare()">Get Square</button>
<button onclick="getcircle()">Get Circle</button>
<script>
function getsquare() {
var outerBox = document.querySelector('.outer-box');
outerBox.innerHTML ='<div class="inner-box">square</div>';
}
function getcircle() {
var outerBox = document.querySelector('.outer-box');
outerBox.innerHTML ='<div class="inner-circle">circle</div>';
}
</script>
</body>
</html> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

คลิกที่ “รับสแควร์ ” เพื่อแสดงสี่เหลี่ยมจัตุรัสภายในสี่เหลี่ยมสีเขียว

ตอนนี้ คลิกที่ “รับแวดวง ” เพื่อแสดงวงกลมภายในสี่เหลี่ยมสีเขียว
