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

method) querySelector()

by kiseno 2025. 1. 14.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const header = document.querySelector('h1')

            header.textContent = 'HEADER'
            header.style.color = 'white'
            header.style.backgroundColor = 'black'
            header.style.padding = '10px'
        })
    </script>
</head>
<body>
    <h1></h1>
</body>
</html>

### HTML Structure
- The body of the document contains an empty `<h1>` element. This is the target for the JavaScript code.

### JavaScript Functionality
- An event listener is added to the `document` object for the `'DOMContentLoaded'` event. This ensures that the JavaScript code inside the callback function will only run after the initial HTML document has been completely loaded and parsed.
- Inside the event listener's callback function, the `<h1>` element is selected using `document.querySelector('h1')`. This method returns the first `<h1>` element found in the document.
- The `textContent` property of the `<h1>` element is set to `'HEADER'`. This changes the text inside the `<h1>` element to "HEADER".
- The style of the `<h1>` element is modified by setting its `color` property to `'white'`, `backgroundColor` property to `'black'`, and `padding` property to `'10px'`. These style changes make the text white, the background color black, and add 10 pixels of padding around the text.

### Result
- Once the page is loaded, the initially empty `<h1>` element will display the text "HEADER" in white on a black background, with a padding of 10 pixels.

### Purpose
This example demonstrates a common use case for the `'DOMContentLoaded'` event: waiting for the HTML to fully load before manipulating elements within the document. It shows how you can dynamically change the content and styling of elements using JavaScript, which is a fundamental concept in web development for creating interactive and dynamic web pages.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

method) Math.random() method  (0) 2025.01.16
method) prototype method  (1) 2025.01.15
method) querySelectorAll() method  (0) 2025.01.13
method) filter()  (0) 2025.01.12
chapter 9) combination of array and object  (0) 2025.01.02