JS의 기본적인 문법들을 훑어봤다.
오늘은 JS에서 HTML의 요소들을 어떻게 가져오는지에 대해서 공부했다.
1. HTML에서 사용할 JS를 명시해준다.
[index.html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class='test'>
<h1>Hello world</h1>
<script src='index.js'></script>
</body>
</html>
2. JS에서 document는 접근할수 있는 html을 가리키는 객체를 의미한다.
콘솔창에 document라고 치면 많은 필드와 값들이 나온다.
이 필드들을 통해서 JS로 HTML에 있는 내용들을 추가하거나 수정할 수 있게된다.
3. querySelecor , getElementById
document객체에 기본적으로 있는 함수들이 있다.
그 중 querySelector와 getElementById를 통해서 원하는 HTML의 항목들에 접근할 수 있다.
[index.js]
const title = document.querySelector('.test h1');
console.log(title)
title에는 index.html의 요소 중 class가 test이고 하위에 있는 h1태그의 내용이 할당된다.
(첫번째로 찾는 항목 : Returns the first element that is a descendant of node that matches selectors.)
getElementById도 이와 비슷한 맥락으로 쓸 수 있다.
querySelecor에서 Id를 통해서 찾으려면 '#' 키워드를 통해서 ID를 명시해주면 된다.
Ref: https://nomadcoders.co/javascript-for-beginners
'JS' 카테고리의 다른 글
JS에서 HTML 기본동작 막기 - preventDefault() (1) | 2024.01.01 |
---|---|
JS에서 HTML element style - className 변경하기 (0) | 2023.12.31 |
JS 배열 관련 함수1 (0) | 2023.12.13 |
[인프런x코드캠프] 훈훈한 Javascript_15日, 16日 (완강) (5) | 2023.02.08 |
[인프런x코드캠프] 훈훈한 Javascript_14日 (2) | 2023.02.06 |