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

คุณสมบัติ nodeName ของ HTML DOM

คุณสมบัติ nodeName ของ HTML DOM จะส่งคืนสตริงที่สอดคล้องกับชื่อของโหนด (node) นั้นๆ

ไวยากรณ์ (Syntax)

Node.nodeName

ค่าที่ส่งคืน (Return Values)

ค่าที่ส่งคืนจะแตกต่างกันไปตามประเภทของโหนด ดังนี้:

  • โหนดองค์ประกอบ (Element nodes): ชื่อแท็ก (Tag name) เป็นตัวพิมพ์ใหญ่
  • โหนดแอตทริบิวต์ (Attribute nodes): ชื่อของแอตทริบิวต์
  • โหนดคอมเมนต์ (Comment nodes): '#comment'
  • โหนดเอกสาร (Document nodes): '#document'
  • โหนดข้อความ (Text nodes): '#text'

หมายเหตุ: ช่องว่าง (Whitespaces) ถูกนับเป็นโหนดข้อความ (text nodes) ด้วย

ตัวอย่างการใช้งาน

ตัวอย่างต่อไปนี้แสดงการใช้คุณสมบัติ nodeName เพื่อดึงชื่อของโหนดต่างๆ เช่น body, input และ comment node

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM nodeName</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-nodeName</legend>
      <label for="example">Example site: </label>
      <input id="urlSelect" type="url" name="urlAddress" value="https://www.example.com" disabled>
      <input type="button" onclick="getNodeNames()" value="Get all names">
      <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 getNodeNames() {
    divDisplay.textContent = 'Body: '+document.body.nodeName;
    divDisplay.textContent += ' & input: '+urlSelect.nodeName;
    divDisplay.textContent += ' & comment: '+commentNode.nodeName;
  }
</script>
</body>
</html>

ผลลัพธ์ (Output)

ก่อนกดปุ่ม "Get all names":

คุณสมบัติ nodeName ของ HTML DOM

หลังกดปุ่ม "Get all names":

คุณสมบัติ nodeName ของ HTML DOM