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

เมธอด isEqualNode() ใน HTML DOM

เมธอด isEqualNode() ใช้ตรวจสอบว่าโหนดสองตัว "เท่ากัน" หรือไม่ (คืนค่า true/false) - ต้องมีประเภท แอตทริบิวต์ และค่าแอตทริบิวต์เหมือนกันทุกประการ รวมถึง childNodes ทั้งหมด

ไวยากรณ์ (Syntax)

firstNode.isEqualNode(secondNode)
📝 หมายเหตุ: โหนดเท่ากันก็ต่อเมื่อ: ประเภทเหมือนกัน, แอตทริบิวต์เหมือนกัน, ค่าแอตทริบิวต์เหมือนกัน, และ childNodes ทั้งหมดเหมือนกัน

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

ตัวอย่างด้านล่างตรวจสอบการลอกเลียนำ (plagiarism) โดยเปรียบเทียบเนื้อหาของสองบทความ:

<!DOCTYPE html>
<html>
<head>
<title>isEqualNode()</title>
<style>
  body { width: 90%; margin: 0 auto; }
  button { border-radius: 10px; display: block; margin: 0 auto; }
  #authorJohn, #authorMaya { border: 1px solid black; border-radius: 10px; }
  #showContent { text-align: center; }
</style>
</head>
<body>
  <div id="authorJohn">
    <h2> Lorem ipsum dolor </h2>
    <h5>By - John</h5>
    <p class="content"> sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div id="authorMaya">
    <h2> Excepteur sint occaecat </h2>
    <h5>By - Maya</h5>
    <p class="content"> sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <button onclick="checkPlagiarism()">Check Plagiarism</button>
  <div id="showContent"></div>
  <script>
    function checkPlagiarism() {
      var articleOne = document.getElementsByClassName("content")[0];
      var articleTwo = document.getElementsByClassName("content")[1];
      var divDisplay = document.getElementById("showContent");
      
      if(articleOne.isEqualNode(articleTwo))
        divDisplay.textContent = 'Content is copied!';
      else
        divDisplay.textContent = 'Content is not copied!';
    }
  </script>
</body>
</html>

ผลลัพธ์

ก่อนคลิกปุ่ม "Check Plagiarism": แสดงสองบทความที่มีหัวข้อต่างกันแต่เนื้อหา (class="content") เหมือนกัน

หลังคลิกปุ่ม "Check Plagiarism": แสดง "Content is copied!" เพราะเนื้อหาใน <p class="content"> เหมือนกันทุกตัวอักษร

หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้