The Wayback Machine - https://web.archive.org/web/20230417101701/https://www.geeksforgeeks.org/how-to-check-two-elements-are-same-using-jquery-javascript/
Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to check two elements are same using jQuery/JavaScript ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 19 Dec, 2022
Improve Article
Save Article
Like Article

Given an HTML document containing two elements and the task is to check whether both elements are same or not with the help of JavaScript. 

Approach 1: Use is() method to check both selected elements are same or not. It takes an element as argument and check if it is equal to the other element. 

Example: This example implements the above approach. 

html




<script src=
</script>
<h1 style="color:green;">
    GeeksForGeeks
</h1>
  
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN" 
   style="color:green; font-size: 20px; font-weight: bold;">
</p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    var id1 = "GFG_UP";
    var id2 = "GFG_UP";
      
    up.innerHTML = "Click on the button to check if "
            + "both elements are equal.<br>" + "id1 = "
            + id1 + "<br>id2 = " + id2;
      
    function GFG_Fun() {
        if ($('#GFG_UP').is($('#GFG_UP'))) {
            down.innerHTML = "Both elements are same";
        } else {
            down.innerHTML = "Both elements are different";
        }
    }
</script>

Output:

 

Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False. Example: This example implements the above approach. 

html




<script src=
</script>
<h1 style="color:green;">
    GeeksForGeeks
</h1>
  
<p id="GFG_UP" 
   style="font-size: 15px; font-weight: bold;">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN" 
   style="color:green; font-size: 20px; font-weight: bold;">
</p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    var id1 = "GFG_UP";
    var id2 = "GFG_DOWN";
      
    up.innerHTML = "Click on the button to check if both"
            + " elements are equal.<br>" + "id1 = "
            + id1 + "<br>id2 = " + id2;
      
    function GFG_Fun() {
        if ($('#GFG_UP')[0] == $('#GFG_DOWN')[0]) {
            down.innerHTML = "Both elements are same";
        } else {
            down.innerHTML = "Both elements are different";
        }
    }
</script>

Output:

 


My Personal Notes arrow_drop_up
Like Article
Save Article