---
title: "What does document.getElementById() return?"  
description: "What does document.getElementById() return?"  
author: "Yash Srivastava"  
published: 2026-07-09  
updated: 2026-07-15  
canonical: https://answers.mindstick.com/qa/116938/what-does-document-getelementbyid-return  
category: "technology"  
tags: ["javascript", "web development"]  
reading_time: 2 minutes  

---

# What does document.getElementById() return?

## Answers

### Answer by Anubhav Sharma

The `document.getElementById()` method returns the **DOM element** whose `id` attribute matches the specified value.

- If an element with the specified ID exists, it returns that **Element** object.
- If no matching element is found, it returns `null`.

### Syntax

```javascript
document.getElementById(id);
```

`id`: A string representing the `id` attribute of the element to retrieve.

### Example 1: Element Found

## HTML

```html
<h1 id="title">Welcome</h1>
```

## JavaScript

```javascript
// Get the element with id="title"
const heading = document.getElementById("title");

// Display the element
console.log(heading);

// Access its text content
console.log(heading.textContent);
```

## Output

```plaintext
<h1 id="title">Welcome</h1>
Welcome
```

### Example 2: Element Not Found

```javascript
// Try to get an element that doesn't exist
const element = document.getElementById("unknown");

// Display the result
console.log(element);
```

## Output

```plaintext
null
```

### Important Notes

- IDs should be **unique** within an HTML document.
- The method returns **only the first matching element** (though duplicate IDs are invalid HTML).
- Since it may return `null`, it's good practice to check the result before using it.

```javascript
const button = document.getElementById("submitBtn");

if (button !== null) {
  console.log("Button found!");
} else {
  console.log("Button not found.");
}
```

### Summary

| Situation | Return Value |
| --- | --- |
| Matching element exists | The corresponding **DOM Element** |
| No matching element exists | `null` |

`document.getElementById()` is one of the most commonly used DOM methods for selecting a specific element by its unique `id`.


---

Original Source: https://answers.mindstick.com/qa/116938/what-does-document-getelementbyid-return

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
