window객체: 브라우저의 창을 대변하면서 JavaScript에서는 최상단에 존재하는 객체window.은 생략할 수 있음console.log(window);
console.log(typeof window); // object

document 객체가 웹 문서의 최상단 객체로 진입점의 역할을 함document객체를 활용하면 웹 페이지 내부에 무엇이든 수정할 수 있고 새로운 콘텐츠를 만들어 낼 수 있음window 객체와 다르게 객체가 아닌 html 태그가 출력 됨console.log(document);
console.log(typeof document); // object

console.dir(document);

DOM 개념에 따르면 문서 내의 모든 태그들은 각각의 객체임


DOM을 활용하면 JavaScript로 html 태그를 객체처럼 자유롭게 다룰 수 있음
콘솔에서 값 자체를 확인하고 싶다면 log메소드를, 객체의 속성들을 살펴보고 싶다면 dir 메소드를 활용하면 좋음


console.log(str, num, bool, arr, obj, func);
console.dir(str, num, bool, arr, obj, func);

4. DOM 객체를 출력하는 결과가 다름


const myTag = document.querySelector('#content')
console.log(myTag);

- 자식 요소 노드
- console.log(myTag.children);

- console.log(myTag.children[1]);

- console.log(myTag.firstElementChild);
- console.log(myTag.lastElementChild);

- 부모 요소 노드
- console.log(myTag.parentElement);

- 형제 요소 노드
- console.log(myTag.previousElementSibling);
- console.log(myTag.nextElementSibling);

- 서로 연결해서 탐색도 가능함
- console.log(myTag.parentElement.nextElementSibling)


console.log(myTag.childNodes)
const myTag = document.querySelector('#list-1');
innerHTML요소 안에 있는 html 자체를 문자열로 리턴해 줌

내부에 있는 줄 바꿈이나 들여쓰기 모두 포함됨
요소 안의 html을 수정 할 때 자주 활용 됨
myTag.innerHTML = '<li>Exotic</li>'; // 요소 수정
myTag.innerHTML += '<li>Exotic</li>'; // 기존 html 마지막 부분에 요소 추가
![]() | ![]() |
|---|
outerHTML
outerHTML에 값을 할당 하게 되면 처음 선택한 요소는 사라짐textContent
innerHTML과 마찬가지로 요소 안의 내용을 수정할 수 있음myTag.textContent = '<li>new text!</li>';
console.log(myTag.textContent);

innerHTML보다는 textContent를 활용하면 원하지 않는 html 코드가 반영되는 걸 막을 수 있음innerHTML, outerHTML 은 내용을 덮어 써버려서 사용할 때 기존 내용을 보존하려면 기존의 값을 한 번 더 써줘야하는 불편함이 있음outerHTML는 한번 프로퍼티를 수정하고 나면 완전히 새로운 요소가 돼서 이후에 그 요소를 다루려면 해당 요소를 다시 찾아야 함
const tomorrow = document.querySelector('#tomorrow');
document.createElement('태그이름')const first = document.createElement('li'): 원하는 태그 이름으로 요소 노드를 만들 수 있음textContent, innerHTML, ...first.textContent = '처음';li 태그가 완성됨NODE.prepend, append, after, beforetomorrow.prepend(first);: 메소드를 호출한 노드의 제일 첫 번째 노드로 파라미터로 전달한 값을 추가할 수가 있음

tomottow.before('문자열', prev);
const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');
tomorrow.remove();
today.children[2].remove();

prepend, append, before, aftertoday.append(tomorrow.children[1]);

tomorrow.children[1].after(today.children[1]);

<body>
<div>
<h1>오늘 할 일</h1>
<ol id="today">
<li class="item">자바스크립트 공부</li>
<li class="item">고양이 화장실 청소</li>
<li class="item">고양이 장난감 쇼핑</li>
</ol>
<h1>내일 할 일</h1>
<ol id="tomorrow" href="https://www.codeit.kr">
<li class="item"><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript">자바스크립트 공부</a></li>
<li class="item">뮤지컬 공연 예매</li>
<li class="item">유튜브 시청</li>
</ol>
</div>
<script src="index.js"></script>
</body>
// HTML 속성 (HTML attribute)
const tomorrow = document.querySelector('#tomorrow');
const item = tomorrow.firstElementChild;
const link = item.firstElementChild;
// id 속성
console.log(tomorrow);
console.log(tomorrow.id);
// class 속성
console.log(item);
console.log(item.className);
// href 속성
console.log(link);
console.log(link.href);
console.log(tomorrow.href); // undefined

getAttribute 메소드를 활용하면 됨// element.getAttribute('속성'): 속성에 접근하기
console.log(tomorrow.getAttribute('href'));
console.log(item.getAttribute('class'));

// element.setAttribute('속성', '값'): 속성 추가(수정) 하기
tomorrow.setAttribute('class', 'list'); // 추가
link.setAttribute('href', 'https://www.codeit.kr'); // 수정

// element.removeAttribute('속성'): 속성제거하기
tomorrow.removeAttribute('href');
tomorrow.removeAttribute('class');

<body>
<div>
<h1 class="title">오늘 할 일</h1>
<ol id="today" class="list today">
<li class="item">자바스크립트 공부</li>
<li class="item">고양이 화장실 청소</li>
<li class="item">고양이 장난감 쇼핑</li>
</ol>
<h1 class="title">내일 할 일</h1>
<ol id="tomorrow" class="list tomorrow">
<li class="item">자바스크립트 공부</li>
<li class="item">뮤지컬 공연 예매</li>
<li class="item">유튜브 시청</li>
</ol>
</div>
<script src="index.js"></script>
</body>
const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');
// style 프로퍼티
today.children[0].style.textDecoration = 'line-through';
today.children[0].style.backgroundColor = '#DDDDDD';
today.children[2].style.textDecoration = 'line-through';
today.children[2].style.backgroundColor = '#DDDDDD';

done클래스에 미리 작성해둔 스타일이 입혀지는 방식.done {
opacity: 0.5;
text-decoration: line-through;
}
today.children[1].className = 'done';

add, remove, toggle 메소드 사용 가능addremove도)toggletrue, false)const item = tomorrow.children[1];
item.classList.add('done');
item.classList.remove('done');
item.classList.toggle('done');
[]를 이용한 css 선택자[속성이름]: 대괄호 안에 있는 속성이름을 가진 태그들을 선택할 수 있음[속성이름="값"]: 속성이름에 해당 값을 가진 태그들을 선택할 수 있음<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS with Codeit</title>
</head>
<body>
<p>할 일 : <b field="title"></b></p>
<p>담당자 : <b field="manager"></b></p>
<p>상태 : <b field="status"></b></p>
<div>
상태 변경:
<button class="btn" status="대기중">대기중</button>
<button class="btn" status="진행중">진행중</button>
<button class="btn" status="완료">완료</button>
</div>
<script src="index.js"></script>
</body>
</html>
[status] {
padding: 5px 10px;
}
[status="대기중"] {
background-color: #FF6767;
color: #FFFFFF;
}
[status="진행중"] {
background-color: #5f62ff;
color: #FFFFFF;
}
[status="완료"] {
background-color: #07c456;
color: #FFFFFF;
}
const fields = document.querySelectorAll('[field]');
console.log(fields);


const fields = document.querySelectorAll('[field]'); // 3개의 b태그들
const task = {
title: '코드 에디터 개발',
manager: 'CastleRing, Raccoon Lee',
status: '',
};
for (let tag of fields) {
const field = tag.getAttribute('field'); // field 속성의 값들 즉, title, manager, status
tag.textContent = task[field]; // task 객체의 key에 대한 값들 즉, '코드 에디터 개발', 'CastleRing, Raccoon Lee'
}


getAttribute 메소드를 활용해서 속성값을 가져오고, setAttribute 메소드를 활용해서 속성값을 설정해주는 원리로 이벤트를 통해 실시간으로 스타일을 변경하거나 데이터를 변경하는데 활용할 수 있음const fields = document.querySelectorAll('[field]');
const task = {
title: '코드 에디터 개발',
manager: 'CastleRing, Raccoon Lee',
status: '',
};
for (let tag of fields) {
const field = tag.getAttribute('field');
tag.textContent = task[field];
}
const btns = document.querySelectorAll('.btn');
for (let btn of btns) {
const status = btn.getAttribute('status'); // status 속성의 값들 즉, 대기중, 진행중, 완료
btn.onclick = function () {
fields[2].textContent = status; // text 값 대기중, 진행중, 완료 설정
fields[2].setAttribute('status', status); //속성 status에 대기중, 진행중, 완료 추가
};
}


data-* 속성이 있음data-로 시작하는 속성은 모두 dataset이라는 프로퍼티에 저장됨data-status라는 속성이 있다면, element.dataset.status라는 프로퍼티에 접근해서 그 값을 가져올 수 있음<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS with Codeit</title>
</head>
<body>
<p>할 일 : <b data-field="title"></b></p>
<p>담당자 : <b data-field="manager"></b></p>
<p>상태 : <b data-field="status"></b></p>
<div>
상태 변경:
<button class="btn" data-status="대기중">대기중</button>
<button class="btn" data-status="진행중">진행중</button>
<button class="btn" data-status="완료">완료</button>
</div>
<script src="index.js"></script>
</body>
</html>
[data-status] {
padding: 5px 10px;
}
[data-status="대기중"] {
background-color: #FF6767;
color: #FFFFFF;
}
[data-status="진행중"] {
background-color: #5f62ff;
color: #FFFFFF;
}
[data-status="완료"] {
background-color: #07c456;
color: #FFFFFF;
}
const fields = document.querySelectorAll('[data-field]');
const task = {
title: '코드 에디터 개발',
manager: 'CastleRing, Raccoon Lee',
status: '',
};
for (let tag of fields) {
const field = tag.dataset.field;
tag.textContent = task[field];
}
const btns = document.querySelectorAll('.btn');
for (let btn of btns) {
const status = btn.dataset.status;
btn.onclick = function () {
fields[2].textContent = status;
fields[2].dataset.status = status;
};
}