01. DOM (Document Object Model) 이란?
DOM (문서 객체 모델) 이란, HTML 또는 XML 문서의 프로그래밍 인터페이스 입니다. DOM은 문서의 구조화된 표현을 제공하며 프로그래밍 언어가 DOM 구조에 접근할 수 있는 방법을 제공하여 문서 구조, 스타일, 내용 등을 변경할 수 있도록 도와줍니다. DOM 은 웹 페이지의 객체 지향 표현이며 자바스크립트와 같은 스크립팅 언어를 이용해 DOM 을 수정할 수 있습니다. DOM을 수정하여 할수 있는 일은
- 새로운 HTML 요소나 속성 추가
- 존재하는 HTML 요소나 속성 제거
- HTML 문서의 모든 HTML 요소 변경
- HTML 문서의 모든 HTML 속성 변경
- HTML 문서의 모든 CSS 스타일 변경
- HTML 문서에 새로운 HTML 이벤트 추가
- HTML 문서의 모든 HTML 이벤트에 반응
02. Document
Document란 웹 페이지에 존재하는 HTML 요소에 접근하여 행동을 하고자 할 때 사용하는 객체 입니다. Document의 속성을 살펴보겠습니다.
- document.documentElement
- document.head
- document.title
- document.body
- document.URL
- document.domain
속성 | 설명 |
documentElement | <html 요소 반환> |
head | <head> 요소 반환 |
title | <title> 요소 반환 |
body | <body> 요소 반환 |
URL | 문서의 URL 주소값을 반환 |
domain | 서버의 도메인명 지정/반환 (권고 x) |
02-1. document 객체를 이용해 HTML 요소 선택
// 1. getElementById
console.log(document.getElementById('green'));
console.log(document.getElementById('red'));
'getElementById '는 태그에 있는 id 속성을 사용하여 해당 태그에 접근 후 작업할때 쓰는 함수입니다.
console.log(document.getElementsByClassName('pink')); //유사배열
console.log(document.getElementsByClassName('pink')[1]);
'getElementsByClassName' 는 태그에 있는 class 속성을 사용하여 해당 태그에 접근 후 작업할때 쓰는 함수입니다. 하나 재밌는 점은 class 는 여러개를 지정할 수 있어서 element 뒤에 s 가 붙습니다. 하하하하하 정말 재밌죠 죄송합니다. getElementsByClassName은 유사배열 형태이기 때문에 대괄호 표기법을 이용하여 접근할 수도 있습니다.
document.getElementsByClassName('pink').forEach((elem) => {
console.log(elem);
});
//유사배열이지 배열은 아니기때문에 실행안됨
다만 찐배열은 아니기때문에 배열 반복문은 실행되지 않습니다.
console.log(document.getElementsByTagName('div'));
'getElementsByTagName' 는 해당 태그에 접근 후 작업할때 쓰는 함수입니다.
console.log(document.getElementsByName('id'));
'getElementsByName'를 사용하면 태그의 이름 (name) 속성갑으로 노드에 접근이 가능합니다.
console.log('=============5. querySelector(css selector)==============');
//5. querySelector(css selector)
// : 처음 발견한 하나만 가지고 옴
console.log(document.querySelector('.pink'));
console.log(document.querySelector('.others'));
console.log(document.querySelector('#green'));
console.log(document.querySelector('div'));
console.log(document.querySelector('[name="id"]'));
console.log('==============6.querySelectorAll (css selector)=============');
//6.querySelectorAll (css selector)
// : 선택자에 해당되는 모든 요소를 선택
console.log(document.querySelectorAll('.pink'));
console.log(document.querySelectorAll('.others'));
console.log(document.querySelectorAll('#green'));
console.log(document.querySelectorAll('div'));
console.log(document.querySelectorAll('[name="id"]'));
console.log(document.querySelectorAll('.pink')[0]);
console.log(document.querySelectorAll('.pink')[1]);
console.log(document.querySelectorAll('.pink')[2]);
console.log(document.querySelectorAll('.pink')[3]);
'querySelector'는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Elements를 반환합니다. 일치하는 요소가 없다면 null 을 반환합니다. 매개변수는 셀렉터로 유효한 CSS 선택자여야 합니다. 선택자를 만족하는 모든 요소의 목록이 필요하다면 'querySelectorAll()'을 사용합니다.
+ 유사배열
여기서 유사배열이란 직접 배열 리터럴로 선언한 array와 다르게 []로 감싸져 있지만 배열이 아닌 것을 유사배열이라고 부릅니다. 유사배열은 배열의 메서드를 쓸 수 없습니다. forEach()반복 메서드를 사용할 수 있지만 nodeList에서는 사용이가능합니다만, HTMLCollection에서는 forEach()메서드를 사용할 수 없습니다. 만약, 반복해야 한다면 array로 변경 후 사용할 수 있습니다. (Array.from()함수 사용)
//유사 배열 (HTMLcollection, NodeList)
//[] 식으로 생긴 배열을 의미. 배열은 아님 !!
//index,length 는 가짐 .. 그치만 배열은 아님..!!!!
//배열과 달리 사용 가능한 메서드가 제한
//nodeList -> forEach() 반복문 사용 가능
console.log('===========forEach ===========');
document.querySelectorAll('.pink').forEach((elem) => console.log(elem));
//HTMLCollection -> forEach() 메서드 사용 x
//반복을 해야 된다? Array 변경 (Array.from())
console.log('===========forEach array 변경===========');
//array 형태로 바꾼다음 forEach 돌기
Array.from(document.getElementsByClassName('pink')).forEach((elem) =>
console.log(elem)
);
//for of 반복문
console.log('===========for of 반복문 ===========');
const pinks = document.querySelectorAll('.pink');
for (let pink of pinks) {
console.log(pink);
}
02-2. document 객체를 이용해 태그 내부 변경
코드로 예를 들어 보겠습니다.
<div id="div1">안녕하세요</div>
라는 div태그를 가진 HTML 문서가 있다고 가정하겠습니다.
//태그 내부 내용 변경
//innerHTML / innerText / textContent
const div1 = document.getElementById('div1');
div1.innerHTML = '여기는 <b>첫번째</b> 태그 ! ';
우선 div1이라는 변수를 정의하여 'div1'해당 ID를 가진 태그에 접근하여 할당합니다. 그리고 innerHTML메소드를 이용하여 태그 내부 내용을 안녕하세요 -> 여기는 첫번째 태그 로 변경합니다. 예시에서 보시듯이 innerHTML 에서는 <b>태그가 문자 그대로가 아닌 태그로 인식됩니다.
//innerText -> <b> 태그가 태그로 인식 안됨
div1.innerText = '여기는 <b>첫번째</b> 태그 ! ';
innerText는 <b>태그가 태그로 인식되지 않고 문자 그대로 인식되기 때문에 <b>첫번째</b> 뭔가 들킨 기분으로 바뀌게 됩니다.
//textContent -> <b> 태그가 태그로 인식 안됨
div1.textContent = '여기는 <b>첫번째</b> 태그 ! ';
console.log(div1);
textContent도 마찬가지로 태그가 인식되지 않습니다.
02-3. document 객체를 이용해 속성 변경 :setAttribute
<a href="https://www.naver.com" id="naver">naver</a>
<img src="./img/pooh.png" alt="pooh" id="pooh" />
해당 HTML 문서가 있다고 가정해보겠습니다.
const naver = document.getElementById('naver');
naver.setAttribute('href', 'https://www.google.com');
//setAttribute('속성명','바꾸려는 속성값')
naver 라는 변수를 만들어 'naver'라는 ID 를 가진 요소에 접근하고 setAttribute 메소드를 통해 href 속성값을 google url로 바꿔줍니다.
const pooh = document.getElementById('pooh');
pooh.setAttribute('src', './img/wawa.png');
'pooh'라는 ID를 가진 요소에 접근 후 pooh라는 변수를 만들고 할당해 줍니다. 할당후 setAttribute 메소드를 통해 src속성값을 바꿔줍니다.
02-4. document 객체를 이용해 속성 가져오기 : getAttribute
console.log(document.getElementById('pooh').getAttribute('src'));
'pooh'라는 ID를 가진 요소에 src 속성값을 가져와 출력하는 코드 입니다.
console.log(document.getElementById('pooh').id); //pooh.id
console.log(document.getElementById('naver').href); //naver.id
속성에 접근은 (.) 연산자로도 가능합니다.
연산자로 속성에 접근하고 = 할당 연산자로 속성 값 까지 변경해보겠습니다.
// 참고 ! 연산자로 속성에 접근하고 = 할당 연산자로 속성 값 변경
document.getElementById('naver').href = '#';
'naver'라는 ID를 가진 요소의 href속성의 속성값을 '#'로 변경한 코드입니다.
02-5. document 객체를 이용해 CSS 지정하기
[html]
<h1>JS 요소 다루기</h1>
<div id="div1">안녕하세요</div>
<a href="https://www.naver.com" id="naver">naver</a>
<img src="./img/pooh.png" alt="pooh" id="pooh" />
<ul id="friends">
<li>이요르</li>
<li id="tigger">티거</li>
<li>피글렛</li>
<li>로빈</li>
</ul>
[js]
const h1 = document.querySelector('h1');
const list = document.querySelectorAll('ul>li'); //유사 배열
우선 css지정을 하기전에 요소들을 변수에 넣어보겠습니다. CSS지정은 style 속성을 이용합니다.
//style.XXX (xxx : camelCase)
// list[0].style.backgroundColor = 'purple';
// list[0].style.fontSize = '20px';
// list[0].style.color = 'yellow';
style 뒤에는 camelCase 로 작성합니다.
for (let li of list) {
li.style.backgroundColor = 'purple';
li.style.fontSize = '20px';
li.style.color = 'yellow';
}
유사배열 형태인 변수 list 는 for of 반복문으로 모두 돌면서 css를 지정할 수도 있습니다.
classList 활용
//CSS 지정 2. classList 활용
//xxx.classList.add
//xxx.classList.remove
//xxx.classList.contains : 있는지 없는지 확인 (t/f)
//xxx.classList.toggle: 있으면 제거, 없으면 추가
//h1 태그에 'add-h1'클래스가 추가 됩니다.
h1.classList.add('add-h1');
//h1 태그에 'add-h1'클래스가 제거 됩니다.
h1.classList.remove('add-h1');
//h1 태그에 'add-h1'클래스가 있는지 true/false로 출력됩니다.
console.log(h1.classList.contains('add-h1'));
//h1 태그에 'add-h1'클래스가 있으면 제거되고 없다면 클래스가 추가됩니다.
h1.classList.toggle('add-h1');
02-6. document 객체를 이용해 요소찾기
[html]
<ul id="friends">
<li>이요르</li>
<li id="tigger">티거</li>
<li>피글렛</li>
<li>로빈</li>
</ul>
//계층 구조 (형제, 자식, 부모 , 조상, 자손)
const friends = document.querySelector('#friends');
const tigger = document.querySelector('#tigger');
//1.자식요소
console.log(friends.children); //유사 배열. 자식 모두 선택
console.log(friends.children[0]); //자식 중 첫번째 자식만 출력
//2.부모 요소
console.log(tigger.parentNode); //tigger 요소 부모 출력 -> ul 태그
console.log(tigger.parentNode.parentNode); //tigger 부모의 부모 출력 -> body 태그
//3.형제 요소
console.log(tigger.previousElementSibling); //이요르
console.log(tigger.nextElementSibling); //피글렛
console.log(tigger.nextElementSibling.nextElementSibling); //로빈
02-7. document 객체를 이용해 요소 생성 및 삭제
[html]
<div class="container"></div>
[js]
//요소 생성, 추가 , 삭제
const container = document.querySelector('.container');
//새로운 요소를 생성
const p = document.createElement('p'); //p태그를 가진 요소 생성
console.log(p); //js로 <p></p> 태그를 만듦
// <p>새로 추가된 p 요소입니다~</p>
p.innerText = '새로 추가된 p 요소입니다~';
p.style.fontWeight = 700; // <p style="font-weight: 700;">새로 추가된 p 요소입니다~</p>
p.style.backgroundColor = 'red'; // <p style="font-weight: 700; background-color: red;">새로 추가된 p 요소입니다~</p>
container 클래스 안에 p태그를 가진 자식요소가 우리가 지정한 text와 css설정을 가지고 생성되~진 않고 아직 설정만 한겁니다. 그래서 이렇게 저장하면 아무것도 안뜹니다. 하하
새로 만든 요소를 추가해보겠습니다. !!!!!
container.append(p);
//container 요소에 맨 마지막 자식으로 p 요소를 추가 합니다. (위에서 만든 p)
//변수 p2 에 p태그를 가진 요소를 만듬 <p></p>
const p2 = document.createElement('p');
//변수 p3 에 p태그를 가진 요소를 만듬 <p></p>
const p3 = document.createElement('p');
//p2변수에 'p2'라는 텍스트 넣기
p2.innerHTML = 'p2';
//p3변수에 'p3'라는 텍스트 넣기
p3.innerHTML = 'p3';
//p2에 'p-2'이름을 가진 class 생성
p2.classList.add('p-2');
//p3에 'p-3'이름을 가진 class 생성
p3.classList.add('p-3');
container.append(p2, p3); //여러개 추가도 가능 !
x.append(y)는 x 요소이 맨 마지막 자식으로 y 요소가 추가되는 것입니다. 맨 처음 자식으로 추가하고 싶다면 perpend를 사용하면 되는데요 예시를 보자면
[html]
<ul id="friends">
<li>이요르</li>
<li id="tigger">티거</li>
<li>피글렛</li>
<li>로빈</li>
</ul>
[js]
const friends = document.querySelector('#friends');
const li1 = document.createElement('li');
li1.textContent = '캉가';
li1이라는 <li> 태그를 가진 요소를 생성하고 '캉가'라는 텍스트를 넣어 줍니다. (<li>캉가</li>)
friends.prepend(li1);
friends 부모 안에 <li>캉가</li>코드가 입력되면서 맨 처음 자식으로 위치하게 됩니다.
const li0 = document.createElement('li');
li0.innerHTML = '<b>친구를 소개합니다. </b>';
friends.prepend(li0);
//요소 삭제
//x.remove() : x 요소삭제
//x.removeChild(y) : x의 자식요소인 y가 삭제됨
const firstli = document.querySelector('li');
console.log(firstli); //친구들을 소개합니다 li 태그
const ul = firstli.parentNode; //ul 태그 id = "friends"
ul.removeChild(firstli); // = firstli.remove()
+append , appendchild 차이
+remove , removechild 차이
'SeSAC > javascript' 카테고리의 다른 글
[SeSACXCodingOn] 웹풀스택과정 06W_3_18 : MVC (+라우터쪼개기) (0) | 2023.08.25 |
---|---|
비동기 처리 (0) | 2023.08.15 |
[SeSACXCodingOn] 웹풀스택과정 4W_11 _01: Node.js + Module + Express (0) | 2023.08.09 |
[SeSACXCodingOn] 웹풀스택과정 2W_06 _04: javascript Event (0) | 2023.08.04 |
[SeSACXCodingOn] 웹풀스택과정 2W_06 _01: javascript_표준객체 (0) | 2023.08.01 |