본문 바로가기
개념/혼자 공부하는 Javascript

chapter 8) Except

by kiseno 2024. 12. 26.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // When there is no document object extracted with the QuerySelector() method
        document.addEventListener('DOMContentLoaded', () => {
            const h1 = document.querySelector('h1')
            h1.textContent = 'hello'
        })

        //basic except
        document.addEventListener('DOMContentLoaded', () => {
            const h1 = document.querySelector('h1')
            if (h1) {
                h1.textContent = 'hello'
            } else {
                console.log('do not extraction of h1 tag')
            }
        })
    </script>
</head>
<body>

</body>
</html>

### Approach 1: Failing Silently
The first event listener tries to find an `<h1>` element using `document.querySelector('h1')` and immediately attempts to set its `textContent` to 'hello'. Since there is no `<h1>` element in the document, this attempt results in a TypeError because `h1` is `null` and you cannot set properties on `null`.

### Approach 2: Handling Absence with a Conditional Check
The second event listener uses the same method to search for an `<h1>` element but includes a conditional check to see if the element actually exists (`if (h1)`). This is a common and recommended practice to avoid errors when attempting to interact with elements that may not be present:
- If the `<h1>` element is found, its `textContent` is set to 'hello'.
- If not, a message is logged to the console indicating that the `<h1>` tag was not found.

### Key Takeaways
- **Graceful Error Handling**: The document demonstrates the importance of checking whether an element exists before trying to interact with it. This approach prevents errors that could interrupt the execution of subsequent JavaScript code.
  
- **Event Listener for DOMContentLoaded**: Both snippets wait for the `DOMContentLoaded` event before attempting to access DOM elements. This is crucial for scripts included in the `<head>` that run before the HTML body is fully parsed. However, in this specific example, since the element does not exist in the body at all, this precaution does not prevent the error in the first approach.

### Conclusion
In real-world applications, always perform checks to ensure that elements exist before manipulating them. This practice enhances the robustness and reliability of your JavaScript code, especially in dynamic environments where elements might be added or removed based on user interactions or other conditions.

728x90
반응형
LIST