Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

NodeValue Property ใน JavaScript HTML DOM คืออะไร?

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 TypenodeValueตัวอย่าง
TextText Content"Hello World"
CommentComment Content"This is a comment"
CDATASectionCDATA Content"..."
Attr (Deprecated)Attribute Value"value"
Elementnull-
Documentnull-

ตัวเลือกที่ดีกว่า (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 ปกติ)