> For the complete documentation index, see [llms.txt](https://edrus.gitbook.io/mt-it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://edrus.gitbook.io/mt-it/2nd-month/week-6/dom-document-object-model/selecting-elements/getelementbyid.md).

# getElementById()

### Introduction to JavaScript getElementById() method

The `document.getElementById()` method returns an `Element` object that represents an HTML element with an id that matches a specified string.

If the document has no element with the specified id, the `document.getElementById()` returns `null`.

Because the id of an element is unique within an HTML document, the `document.getElementById()` is a quick way to access an element.

Unlike the `querySelector()` method, the `getElementById()` is only available on the `document` object, not other elements.

The following shows the syntax of the `getElementById()` method:

```javascript
const element = document.getElementById(id);Code language: JavaScript (javascript)
```

In this syntax, the id is a string that represents the id of the element to select. The id is case-sensitive. For example, the `'root'` and `'Root'` are totally different.

The `id` is unique within an HTML document. However, HTML is a forgiving language. If the HTML document has multiple elements with the same id, the `document.getElementById()` method returns the first element it encounters.

### JavaScript getElementById() method example

Suppose you have the following HTML document:

```xml
<html>
    <head>
        <title>JavaScript getElementById() Method</title>
    </head>
    <body>
        <p id="message">A paragraph</p>
    </body>
</html>Code language: HTML, XML (xml)
```

The document contains a `<p>` element that has the `id` attribute with the value `message`:

```javascript
const p = document.getElementById('message');
console.log(p);Code language: JavaScript (javascript)
```

Output:

```xml
<p id="message">A paragraph</p>Code language: HTML, XML (xml)
```

After selecting an element, you can [add styles to the element](https://www.javascripttutorial.net/dom/css/add-styles-to-an-element/), manipulate its [attributes](https://www.javascripttutorial.net/dom/attributes/set-the-value-of-an-attribute/), and traverse to [parent](https://www.javascripttutorial.net/javascript-dom/javascript-get-parent-element-parentnode/) and [child elements](https://www.javascripttutorial.net/javascript-dom/javascript-get-child-element/).

### Summary

* The `document.getElementById()` returns a DOM element specified by an `id` or `null` if no matching element found.
* If multiple elements have the same `id`, even though it is invalid, the `getElementById()` returns the first element it encounters.
