Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính nodeValue trong HTML DOM


Giới thiệu

Thuộc tính nodeValue trong HTML DOM trả về hoặc thiết lập chuỗi tương ứng với giá trị của node.

Cú pháp

Lấy giá trị chuỗi:

Node.nodeValue

Giá trị trả về tùy loại node:

  • null cho document node và element node
  • Giá trị của thuộc tính (attribute value) cho attribute node
  • Nội dung văn bản cho text node và comment node

Thiết lập nodeValue:

Node.nodeValue = string

Lưu ý: Khoảng trắng (whitespace) được coi là text node.

Ví dụ

Ví dụ kiểm tra xem "Bina" có trong danh sách sinh viên không bằng cách duyệt text node của các <li>.

<!DOCTYPE html> <html> <head> <title>HTML DOM nodeValue</title> <style> 
  form { width:70%; margin: 0 auto; text-align: center; } 
  * { padding: 2px; margin:5px; } 
  input[type="button"] { border-radius: 10px; } 
  ul{ width: 30%; margin: 0 auto; } 
</style> </head> <body> 
  <form> 
    <fieldset> 
      <legend>HTML-DOM-nodeValue</legend> 
      <h3>Students</h3> 
      <ul> 
        <li>Adam</li> 
        <li>Alex</li> 
        <li>Bina</li> 
        <li>Eden</li> 
        <li>Rajesh</li> 
        <li>Zampa</li> 
      </ul> 
      <input type="button" onclick="checkForBina()" value="Confirm for Bina"> 
      <div id="divDisplay"></div> 
    </fieldset> 
  </form> 
  <script> 
    var divDisplay = document.getElementById("divDisplay"); 
    var studentList = document.getElementsByTagName("li"); 
    var status = 'not Present'; 
    function checkForBina() { 
      for(var i=0; i<studentList.length; i++){ 
        if(studentList[i].childNodes[0].nodeValue === 'Bina') 
          status = 'Present'; 
      } 
      divDisplay.textContent = 'Bina is ' + status; 
    } 
  </script> </body> </html>

Kết quả

Trước khi nhấn Confirm for Bina:

Thuộc tính nodeValue trong HTML DOM

Sau khi nhấn Confirm for Bina:

Thuộc tính nodeValue trong HTML DOM