How to usethe document.getElementById() method in Javascript
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.
html
<!DOCTYPE html> < html lang = "en" > < head > < title > How to Check an Element with Specific ID Exists using JavaScript ? </ title > </ head > < body > < h1 style = "color:green;" > w3wiki </ h1 > < p > Click on button to check if element exists using JavaScript </ p > < button onClick = "GFG_Fun()" > click here </ button > < p id = "result" ></ p > < script > let res = document.getElementById('result'); function GFG_Fun() { let el = document.getElementById('GFG'); if (el != null) { el_down.innerHTML = "Element Exists"; } else { el_down.innerHTML = "Element Not Exists"; } } </ script > </ body > </ html > |
Output:
How to Check an Element with Specific ID Exists using JavaScript ?
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.
There are two approaches that are discussed below:
Table of Content
- Using document.getElementById() method
- Using document.getElementById() and JSON.stringify() method