![]() |
VOOZH | about |
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:
Table of Content
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:
👁 ImageFirst, 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:
👁 ImageThe 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: