<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
const headers = document.querySelectorAll('h1')
headers.forEach((header) => {
header.textContent = 'HEADER'
header.style.color = 'white'
header.style.backgroundColor = 'black'
header.style.padding = '10px'
})
})
</script>
</head>
<body>
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
</body>
</html>
### HTML Structure
- The body of the document contains four empty `<h1>` elements. These are the targets for the JavaScript code to modify.
### JavaScript Functionality
- Similar to the previous example, an event listener is added to the `document` object for the `'DOMContentLoaded'` event. This ensures the JavaScript code inside the callback function executes only after the entire document has been fully loaded.
- The key difference in this script is the use of `document.querySelectorAll('h1')` to select all `<h1>` elements in the document. This method returns a NodeList containing all the `<h1>` elements found.
- The `forEach` method is used to iterate over each element in the NodeList. For each `<h1>` element, the following changes are made:
- The `textContent` is set to `'HEADER'`, changing the text inside each `<h1>` element to "HEADER".
- The `style.color` property is set to `'white'`, changing the text color to white.
- The `style.backgroundColor` property is set to `'black'`, setting the background color of each `<h1>` to black.
- The `style.padding` property is set to `'10px'`, adding padding around the text in each `<h1>`.
### Result
- After the document has loaded, all four `<h1>` elements will display the text "HEADER" in white on a black background, with a padding of 10 pixels around the text.
### Purpose
- This example illustrates a practical approach to manipulating multiple elements simultaneously using `querySelectorAll` and `forEach`. It highlights the power of JavaScript for creating dynamic and interactive web pages by allowing for the bulk modification of elements based on their shared characteristics, in this case, their tag name (`<h1>`).
Such techniques are fundamental in web development, enabling developers to efficiently apply changes across multiple elements without needing to individually select and modify each one. This not only simplifies the code but also enhances its maintainability and scalability.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
method) prototype method (1) | 2025.01.15 |
---|---|
method) querySelector() (0) | 2025.01.14 |
method) filter() (0) | 2025.01.12 |
chapter 9) combination of array and object (0) | 2025.01.02 |
chapter 9) Override (2) | 2025.01.01 |