Property nodeValue ใช้ อ่าน/ตั้งค่า ค่าของ Node ใช้กับ Node Types ที่มีค่า: Text, Comment, CDATASection, Attr (Deprecated) — ไม่ทำงานกับ Element Node
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<p>Get the node value</p>
<button>Demo Button Text</button>
<script>
var val = document.getElementsByTagName("BUTTON")[0];
var res = val.childNodes[0].nodeValue; // Text Node ภายใน Button
document.write("<br>Node Value: " + res);
</script>
</body>
</html>
คำอธิบาย
val.childNodes[0]— Text Node แรกภายใน Button ("Demo Button Text").nodeValue— คืนค่า String ของ Text Node นั้น- ผลลัพธ์:
Node Value: Demo Button Text
Node Types และ nodeValue
| Node Type | nodeValue | ตัวอย่าง |
|---|---|---|
Text | Text Content | "Hello World" |
Comment | Comment Content | "This is a comment" |
CDATASection | CDATA Content | "..." |
Attr (Deprecated) | Attribute Value | "value" |
Element | null | - |
Document | null | - |
ตัวเลือกที่ดีกว่า (Modern)
- Element Text:
element.textContent(รวมทั้งหมด) หรือelement.innerText(Visible Only) - Attribute:
element.getAttribute('name')หรือelement.name - Text Node โดยตรง:
textNode.data(Alias ของ nodeValue)
ใช้ nodeValue เมื่อ: จัดการ Text Node/Comment Node โดยตรง (Rare ใน App ปกติ)