Giới thiệu
Thuộc tính nodeType trong HTML DOM trả về một số (number) tương ứng với loại (type) của node.
Cú pháp
Lấy giá trị số:
Node.nodeType
Các giá trị trả về phổ biến:
1- Element node (phần tử)2- Attribute node (thuộc tính)3- Text node (văn bản)8- Comment node (chú thích)
Lưu ý: Khoảng trắng (whitespace) được coi là text node.
Ví dụ
Ví dụ lấy nodeType của body, input element và một comment node được tạo động.
<!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>
Kết quả
Trước khi nhấn Get all Types:

Sau khi nhấn Get all Types:
