คุณสมบัติ HTML DOM nodeType ส่งคืนตัวเลขที่สอดคล้องกับประเภทของโหนด (node)
ไวยากรณ์ (Syntax)
การส่งคืนค่าตัวเลข:
Node.nodeType
ที่นี่ ค่าที่ส่งคืนอาจเป็นดังต่อไปนี้:
- ตัวเลข '1' สำหรับ element nodes
- ตัวเลข '2' สำหรับ attribute nodes
- ตัวเลข '3' สำหรับ text nodes
- ตัวเลข '8' สำหรับ comment nodes
หมายเหตุ: ช่องว่าง (whitespaces) ถูกนับเป็น text nodes เท่านั้น
ตัวอย่างการใช้งาน
<!DOCTYPE html> <html> <head> <title>HTML DOM nodeType</title> <style>
form {
width: 70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin: 5px;
}
input[type="button"] {
border-radius: 10px;
}
</style> </head> <body>
<form>
<fieldset>
<legend>HTML-DOM-nodeType</legend>
<label for="example">Example site: </label>
<input id="urlSelect" type="url" name="urlAddress" value="https://www.example.com" disabled>
<input type="button" onclick="getNodeTypes()" value="Get all Types">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var urlSelect = document.getElementById("urlSelect");
var commentNode = document.createComment("My Example URL");
urlSelect.appendChild(commentNode);
var divDisplay = document.getElementById("divDisplay");
function getNodeTypes() {
divDisplay.textContent = 'Body: ' + document.body.nodeType;
divDisplay.textContent += ' & input: ' + urlSelect.nodeType;
divDisplay.textContent += ' & comment: ' + commentNode.nodeType;
}
</script>
</body> </html>
ผลลัพธ์
ก่อนคลิก 'Get all Types':

หลังคลิก 'Get all Types':
