
<body>
<h1>Hello</h1>
<p>Welcome!</p>
</body>
document
└── html
└── body
├── h1
└── p

const heading = document.querySelector("h1"); // h1 요소 선택
heading.textContent = "안녕!"; // 텍스트 바꾸기
heading.style.color = "blue"; // 스타일 바꾸기
<button class="button"> Click Me </button>
// DOM 안에 클래스가 button 이라는 이름을 가진 요소에 접근
var button = document.querySelector('.button');
// DOM 안에 있는 요소의 스타일을 직접 변경(DOM 조작)
button.onclick = function () {
this.style.backgroundColor = "red";
};


브라우저가 서버에서 페이지에 대한 HTML 응답을 받고
화면에 표시하기 전에 여러 단계가 있음🙋♀️
👇 웹 브라우저가 HTML 문서를 읽고 스타일 입히고 뷰포트에 표시하는 과정


<!DOCTYPE html>
<html>
<head><title>테스트</title></head>
<body>
<form id="loginForm" action="/login" method="post">
<input type="text" name="username" />
</form>
<a href="https://naver.com">네이버</a>
<a>텍스트만</a> <!-- href 없으면 links에 포함 안 됨 -->
</body>
</html>
console.log(document.baseURI); // 전체 주소(절대 경로 반환)
console.log(document.head); // <head> 요소
console.log(document.body); // <body> 요소
console.log(document.doctype.name); // "html"
console.log(document.cookie); // 쿠키 값
console.log(document.forms.length); // 1
console.log(document.forms[0].id); // "loginForm"
console.log(document.forms[0].action); // "/login"
console.log(document.forms[0].method); // "post"
console.log(document.links.length); // 1 (href 있는 <a>만 포함)

<!DOCTYPE html>
<html>
<head>
<title>폼 submit + 쿠키 예제</title>
</head>
<body>
<form id="loginForm" action="/login" method="POST">
<input type="text" name="username" placeholder="아이디 입력" />
<input type="password" name="password" placeholder="비밀번호 입력" />
<button type="button" onclick="handleLogin()">로그인</button>
</form>
<script>
function handleLogin() {
// 예: 로그인 전에 쿠키를 하나 저장해보자 (실제로는 로그인 후 저장)
document.cookie = "loginStatus=tryLogin; path=/";
// 첫 번째 폼을 submit함 → <form action="/login" method="POST">로 요청 감
document.forms[0].submit();
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>fetch 로그인 예시</title>
</head>
<body>
<input type="text" id="username" placeholder="아이디 입력" />
<input type="password" id="password" placeholder="비밀번호 입력" />
<button onclick="login()">로그인</button>
<script>
async function login() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
try {
const response = await fetch("/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ username, password })
});
if (response.ok) {
// 로그인 성공 시 쿠키 저장 (예: 로그인 상태 쿠키)
document.cookie = "loggedIn=true; path=/";
alert("로그인 성공!");
// 페이지 이동 등
} else {
alert("로그인 실패!");
}
} catch (error) {
console.error("로그인 오류:", error);
}
}
</script>
</body>
</html>
<div id="box">ID로 선택됨</div>
<p class="text">첫 번째 텍스트</p>
<p class="text">두 번째 텍스트</p>
// ✅ getElementById
const box = document.getElementById('box');
console.log(box);
// 리턴: <div id="box">ID로 선택됨</div>
// ✅ querySelector
const firstText = document.querySelector('.text');
console.log(firstText);
// 리턴: <p class="text">첫 번째 텍스트</p>
| 항목 | getElementId( ) | querySelector( ) |
|---|---|---|
| 인자 | 요소의 id ( 문자열, #️⃣ 안 씀❌ ) | CSS 선택자 ( id = #️⃣id, 클래스 = .class ) |
| 리턴값 | 일치하는 1개의 요소 | CSS 선택자에 맞는 첫 번째 요소 |
| 사용 상황 | 특정 🆔 요소만 선택할 때 | 클래스, 태그, 속성 등 다양한 선택자로 요소를 찾을 때 |
| 예 | getElementById('dox') | querySelector('.text') |
<h1 id="header-heading" class="title main">
안녕하세요
</h1>
const heading = document.getElementById('header-heading');
console.log(heading.className);
// 출력: "title main" (← class 속성값이 문자열로 나옴)
document.getElementById('header-heading').className = 'highlight';
// 결과 : <h1 id="header-heading" class="highlight">안녕하세요</h1>
<h1 id="header-container">
안녕하세요
</h1>
const headerContainer = document.getElementById('header-container');
// ✅ 스타일 변경
headerContainer.style.fontSize = '10px'; // 폰트 크기 변경
headerContainer.style.display = 'none'; // 화면에서 숨김
// ✅ 콘텐츠 변경
// 텍스트만 삽입 (태그 해석 X)
headerContainer.textContent = 'Text Content';
// 사람이 보는 기준의 텍스트 (보이는 것 기준)
headerContainer.innerText = 'Inner Text';
// HTML 코드로 삽입 (태그 해석 O)
headerContainer.innerHTML = '<span>Inner HTML</span>';
<div id='my_div'>
안녕하세요? 만나서 반가워요.
<span style='display:none'>숨겨진 텍스트</span>
</div>
<input type='button'
value='innerHTML'
onclick='getInnerHTML()'/>
<input type='button'
value='innerText'
onclick='getInnerText()'/>
<input type='button'
value='textContent'
onclick='getTextContent()'/>
function getInnerHTML() {
const element = document.getElementById('my_div');
alert(element.innerHTML);
}
function getInnerText() {
const element = document.getElementById('my_div');
alert(element.innerText);
}
function getTextContent() {
const element = document.getElementById('my_div');
alert(element.textContent);
}



| 속성 | 태그 포함 | 숨겨진 텍스트 포함 | 줄바꿈/공백 처리 | 설명 요약 |
|---|---|---|---|---|
| innerHTML | ⭕ | ⭕ ( display:none도 포함 ) | ❌ 무시( HTML로 직접 넣어야 함 ) | HTML 태그까지 문자열로 가져옴( 삽입함 ) |
| innerText | ❌ | ❌ ( 화면에 보이는 것만 표시 ) | 👀 ( 눈에 보이는 줄바꿈 반영 ) | 화면에 표시된 텍스트만 가져옴 |
| textContent | ❌ | ⭕ ( 숨겨진 텍스트도 포함 ) | ❌ ( 줄바꿈은 있음, 브라우저는 안 보임 ) | HTML 무시, 전체 텍스트를 그대로 가져옴 |
아이디 선택 :
#아이디
클래스 선택 :.클래스
태그 선택 :태그명
<div id="header">헤더</div>
<p class="intro">소개 글</p>
<ul>
<li>첫 번째 항목</li>
<li>두 번째 항목</li>
</ul>
// #아이디로 선택
const headerElement = document.querySelector('#header');
console.log(headerElement.textContent); // 출력: 헤더
// .클래스명으로 선택
const introElement = document.querySelector('.intro');
console.log(introElement.textContent); // 출력: 소개 글
// 태그명으로 선택
const firstListItem = document.querySelector('li');
console.log(firstListItem.textContent); // 출력: 첫 번째 항목
<div class="container">
<p>첫 번째 문단</p>
<p>두 번째 문단</p>
<p>세 번째 문단</p>
<p>네 번째 문단</p>
<p>다섯 번째 문단</p>
</div>
<script>
// :nth-child(2) - 두 번째 문단 선택
const secondParagraph = document.querySelector('.container p:nth-child(2)');
secondParagraph.style.color = 'red'; // 두 번째 문단을 빨간색으로 설정
// :last-child - 마지막 문단 선택
const lastParagraph = document.querySelector('.container p:last-child');
lastParagraph.style.fontWeight = 'bold'; // 마지막 문단을 굵은 글씨로 설정
// :nth-child(odd) - 홀수 번째 문단들 선택
const oddParagraphs = document.querySelectorAll('.container p:nth-child(odd)');
oddParagraphs.forEach(paragraph => {
paragraph.style.backgroundColor = 'lightblue'; // 홀수 문단의 배경을 하늘색으로 설정
});
// :nth-child(even) - 짝수 번째 문단들 선택
const evenParagraphs = document.querySelectorAll('.container p:nth-child(even)');
evenParagraphs.forEach(paragraph => {
paragraph.style.backgroundColor = 'lightgreen'; // 짝수 문단의 배경을 초록색으로 설정
});
</script>
const items = document.getElementsByClassName('list-group-item');
console.log(items);

console.log(items[0]);

items[0].style.color = 'blue'; // 첫번째 요소만 폰트가 파란색으로 변경됨
items[3].textContent = 'Hi'; // 세번째 요소의 텍스트가 Hi로 변경됨
// (태그의 이름을 작성하면 됨)
let list = document.getElementsByTagName('li');
// 이것도 위와 같이 첫번째 요소의 텍스트 색상이 빨간색으로 변경됨
list[0].style.color = 'red';
list = Array.from(list);
console.log(list);



const items = document.querySelectorAll('ul.list-group li.list-group-item');
console.log(items);

items.forEach(function (item, index) {
item.textContent = `${index}. List`
})
/* 출력
0. List
1. List
2. List
3. List
4. List
*/
const liOdd = document.querySelectorAll('li:nth-child(odd)');
liOdd.forEach(function (li, index) {
li.style.background = 'gray';
})
const liEven = document.querySelectorAll('li:nth-child(even)');
for (let i = 0; i < liEven.length; i++) {
liEven[i].style.background = 'lightgray'
}
