|
| 1 | +--- |
| 2 | +Title: '.getElementById()' |
| 3 | +Description: 'Retrieve the first HTML element with the specified id, returning null if no match is found.' |
| 4 | +Subjects: |
| 5 | + - 'Web Development' |
| 6 | + - 'Web Design' |
| 7 | +Tags: |
| 8 | + - 'DOM' |
| 9 | + - 'Elements' |
| 10 | + - 'JavaScript' |
| 11 | + - 'Methods' |
| 12 | +CatalogContent: |
| 13 | + - 'introduction-to-javascript' |
| 14 | + - 'paths/front-end-engineer-career-path' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.getElementById()`** method is a commonly used function in the Document Object Model (DOM) that allows developers to retrieve an HTML element by its `id` attribute. This method is part of the `document` object and returns the first element that matches the specified `id`. If no element is found, it returns `null`. |
| 18 | + |
| 19 | +## Key Characteristics |
| 20 | + |
| 21 | +- **Fast and efficient**: Since IDs are unique, this method quickly retrieves elements without searching the entire DOM. |
| 22 | +- **Returns a single element**: It always returns one element (or `null` if not found). |
| 23 | +- **Case-sensitive**: The provided `id` must match exactly, including letter casing. |
| 24 | + |
| 25 | +> **Note**: If multiple elements share the same `id` (which is invalid HTML), `getElementById()` still returns only the first match. |
| 26 | +
|
| 27 | +## Syntax |
| 28 | + |
| 29 | +```pseudo |
| 30 | +document.getElementById("elementId"); |
| 31 | +``` |
| 32 | + |
| 33 | +- `elementId` (string): The `id` of the element to retrieve. |
| 34 | + |
| 35 | +## Example |
| 36 | + |
| 37 | +The following example demonstrates the usage of the `.getElementById()` method: |
| 38 | + |
| 39 | +```html |
| 40 | +<!DOCTYPE html> |
| 41 | +<html lang="en"> |
| 42 | + <head> |
| 43 | + <title>getElementById Example</title> |
| 44 | + </head> |
| 45 | + <body> |
| 46 | + <p id="demo">Hello, World!</p> |
| 47 | + <button onclick="changeText()">Click Me</button> |
| 48 | + |
| 49 | + <script> |
| 50 | + function changeText() { |
| 51 | + let element = document.getElementById('demo'); |
| 52 | + element.innerHTML = 'Text changed!'; |
| 53 | + } |
| 54 | + </script> |
| 55 | + </body> |
| 56 | +</html> |
| 57 | +``` |
| 58 | + |
| 59 | +In this example, the `getElementById("demo")` function retrieves the `<p>` element with `id="demo"` and the `innerHTML` property is updated when the button is clicked. |
| 60 | + |
| 61 | +The output will look like: |
| 62 | + |
| 63 | + |
0 commit comments