VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-check-an-element-with-specific-id-exists-using-javascript/

⇱ How to Check an Element with Specific ID Exists using JavaScript ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Check an Element with Specific ID Exists using JavaScript ?

Last Updated : 12 Jul, 2025

Given an HTML document containing some elements and the elements contain some id attribute. The task is to check whether the element with a specific ID exists or not using JavaScript.

Below are the approaches to check an element with specific ID exists or not using JavaScript: 

Approach 1: Using the document.getElementById() method

First, we will use document.getElementById() to get the ID and store the ID into a variable. Then compare the element (a variable that stores ID) with 'null' and identify whether the element exists or not.

Example: This example shows the implementation of the above-explained approach.

Output:

👁 Image

Approach 2: Using document.getElementById() and JSON.stringify() method

First, we will use document.getElementById() method to get the ID and store the ID into a variable. Then use JSON.stringify() method on the element (variable that store ID) and compare the element with 'null' string and then identify whether the element exists or not.

Example: This example shows the implementation of the above-explained approach.

Output:

👁 Image

Approach 3: Using document.querySelector() Method

The document.querySelector() method returns the first element that matches a specified CSS selector. If no elements match, it returns null. This method is more versatile than getElementById() because it allows for more complex selectors (e.g., classes, attributes).

Example:

Output:

👁 Image
Check if an Element with Specific ID Exists
Comment