220518 Do it! 자바스크립트 5

연주·2022년 5월 18일
0

TIL

목록 보기
6/37

Do it! 자바스크립트

8강 웹 문서를 다루는 방법, 문서 객체 모델(DOM)

1. 문서 객체 모델이란?

Document Object Model
웹 문서의 모든 요소를 자바스크립트를 이용하여 조작할 수 있도록 객체를 사용해 문서를 해석하는 방법.

  • DOM을 사용하지 않고 상세 설명 가리기
<h3 style="visibility:hidden">상세 설명</h3>
    <p style="visibility:hidden">2차 세계대전 이후 설립된 게뎁 농장은 유기농 인증 농장으로 여성의 고용 창출과 지역사회 발전에 기여하며 3대째 이어져 내려오는 오랜 역사를 가진 농장입니다. 게뎁 농장은 SCAA 인증을 받은 커피
      품질관리 실험실을 갖추고 있어 철처한 관리를 통해 스페셜티 커피를 생산합니다.</p>

document.querySelector('#detail h3').style.visibility = "hidden"
document.querySelector('#detail p').style.visibility = "hidden"
  • DOM 트리 - DOM 구조는 나무처럼 생겼다
<body>                    // 부모 요소
	<h1>제목</h1>          // 자식 요소
	<p>본문</p>            // 자식 요소
</body>

DOM트리는 웹 문서 요소를 다음과 같이 표현한다.

  • 웹 문서의 태그는 요소(Element) 노드로 표현합니다.
  • 태그가 품고 있는 텍스트는 해당 요소 노드(태그)의 자식 노드인 텍스트(Text) 노드로 표현합니다.
  • 주석은 주석(Comment) 노드로 표현합니다.

2. DOM 요소에 접근하기

  • DOM 요소에 접근하는 여러 가지 방법
    ▪ DOM 요소를 id 선택자로 접근하는 함수 - getElementByld( )
document.getElementById("heading")
<h1 id=​"heading">​에디오피아 게뎁​</h1>​

document.getElementById("heading").onclick = function(){
    this.style.fontSize = "5em"
}

▪ DOM 요소를 class 값으로 찾아내는 함수 - getElementsByClassName( )

document.getElementsByClassName("accent")
HTMLCollection(2) [span.accent, span.accent]
document.getElementsByClassName("accent")[0]
<span class=​"accent">​게뎁농장​</span>​
document.getElementsByClassName("accent")[0].style.textDecoration = "underline"
'underline'

▪ DOM 요소를 태그 이름으로 찾아내는 함수 - getElemetsByTagName( )

document.getElementsByTagName("h2")
HTMLCollection(2) [h2.bright, h2]0: h2.bright1: h2length: 2[[Prototype]]: HTMLCollection
document.getElementsByTagName("h2")[0].style.backgroundColor = "#eee"
'#eee'

▪ DOM 요소를 다양한 방법으로 찾아주는 함수 - querySelector(), querySelectorAll()

document.querySelector("#heading")
<h1 id=​"heading" style=​"font-size:​ 5em;​">​에디오피아 게뎁​</h1>​
document.querySelectorAll(".accent")
NodeList(2) [span.accent, span.accent]0: span.accent1: span.accentlength: 2[[Prototype]]: NodeList
document.querySelectorAll(".accent")[1].style.backgroundColor="yellow"
'yellow'

getElementByld( ) 함수와 querySelector( ) 함수의 차이
getElementByld( ) 함수는 DOM 노드 중에서도 요소 노드까지만 접근
querySelector( ) 함수는 요소 노드 뿐만 아니라, 텍스트 노드 속성 노드까지 접근 가능

3. 웹 요소의 속성 가져와서 수정하기

  • HTML 태그 속성을 가져오거나 수정하는 함수 - getAttribute( ), setAttribute( )
document.querySelector("#prod-img > img").getAttribute("src")
'images/coffee-pink.jpg'
document.querySelector("#prod-img > img").setAttribute("src","images/coffee-blue.jpg")
  • 선택한 이미지 표시하기 - 태그 속성을 사용해 상품 이미지 변경하기
var bigPic = document.querySelector("#cup")
var smallPic = document.querySelectorAll(".small")

for (var i = 0 ; i < smallPic.length; i++){
    smallPic[i].onclick = showBig;    
}

function showBig(){
    var newPic = this.src;
    bigPic.setAttribute("src",newPic);
}

4. DOM에서 이벤트 처리하기

  • addEventListener( ) 함수 사용하기
	var pic = document.querySelector('#pic');
    pic.addEventListener("mouseover","changePic",false);
    pic.addEventListener("mouseover","originPic",false);
    //moseover 이벤트유형, changePic 함수 , false 기본값.
    
		function changePic() {			
			pic.src = "images/boy.png";
    }
    function drawBorder() {
      pic.style.border = "2px dotted #666";
    }

5. 웹 요소 내용과 스타일 가져와서 수정하기

  • DOM으로 CSS 속성에 접근하고 수정하기
    ▪ 텍스트 색상 바꾸기
document.querySelector("#heading").style.color= "white"
'white'
document.querySelector("#heading").style.backgroundColor = "gray"
'gray'
var myRect = document.querySelector("#rect");
myRect.addEventListener("mouseover", function() {  // mouseover 이벤트 처리
	myRect.style.backgroundColor = "green";  // myRect 요소의 배경색 
	myRect.style.borderRadius = "50%";  // myRect 요소의 테두리 둥글게 처리
});
myRect.addEventListener("mouseout", function() {  // mouseout 이벤트 처리
	myRect.style.backgroundColor = "";  // myRect 요소의 배경색 지우기 
	myRect.style.borderRadius = "";  // myRect 요소의 테두리 둥글게 처리 안 함
});
  • 상세 설명 보기/닫기 - 상세 설명 링크 만들기
		var isOpen = false;
		var cup = document.querySelector("#cup");
		var samallpics = document.querySelectorAll("#small");		
		
		
		var bigPic = document.querySelector("#cup");  
		var smallPics = document.querySelectorAll(".small");  

		for(i=0; i<smallPics.length; i++) {
			smallPics[i].addEventListener("click", function() {
				newPic = this.src;
				bigPic.setAttribute("src", newPic);
			});
		}
		
		var view = document.querySelector("#view");
		view.addEventListener("click", function(){
			if(isOpen === false){
				document.querySelector("#detail").style.display = "block";
				view.innerText = "상세 설명 닫기";
				isOpen = true;
			}
			else{
				document.querySelector("#detail").style.display = "none";
				view.innerText = "상세 설명 보기";
				isOpen = false;
			}
		})
  1. DOM에 요소 추가하기
  • DOM에 새로운 노드 추가하는 방법
<p class = "accent">주문이 완료되었습니다</p>
// p - p 요소 노드
   class="accent" - 속성노드
   "주문이 완료되었습니다" - 텍스트노드
  • 웹 문서에 새로운 노드 추가하기
var newP = document.createElement("p")
// 새로운 요소를 만드는 함수, p 태그에 해당하는 요소 노드
var newText = document.createTextNode("주문이 완료되었습니다.")
// 새 요소 만드는, 텍스트 노드 만드는 함수
newP.appendChild(newText)    // 텍스트 노드를 자식 노드로 연결해 주는 함수
"주문이 완료되었습니다."
document.body.appendChild(newP)
<p>​주문이 완료되었습니다.​</p>​
var attr = document.createAttribute("class")  // 새로운 속성 노드를 만드는 함수
undefined
attr.value = "accent"
'accent'
newP.setAttributeNode(attr)       // 속성 노드를 요소 노드로 연결
null
  • 참가 신청 명단 프로그램 만들기 - 새 노드 추가하고 표시하기
function newRegister(){
    var newP = document.createElement("p");  // 새 p 요소 만들기
    var userName = document.querySelector("#userName");       // 텍스트 필드 내용 가져오기
    var newText = document.createTextNode(userName.value);    // 새 텍스트 노드 만들기
    newP.appendChild(newText);     // newText 노드를 newP 노드의 자식 노드로 연결

    var nameList = document.querySelector("#nameList");   //#nameList를 가져옴
    nameList.appendChild(newP);    // newP 노드를 nameList 노드의 자식 노드로 연결
    userName.value = "";   // 다른 이름을 입력할 수 있도록 텍스트 필드 비우기

}

7. 추가한 노드 순서 바꾸거나 삭제하기

  • DOM 트리를 활용해 원하는 노드 다루기
    ▪ 자식 노드 확인하기 - hasChildNodes( ) 함수
document.querySelectorAll("p")[0].hasChildNodes()
true    // 자식 노드 존재

▪ 자식 노드 접근하기 - childNodes 속성

document.querySelector("#nameList").childNodes
NodeList(7) [text, p, text, p, text, p, text]   // 7개의 자식 요소 확인

▪ 원하는 위치에 노드 삽입하기 - insertBefore( ) 함수

nameList.insertBefore(nameList.children[2],nameList.children[0])
<p>​…​</p>​"도레미 "<span class=​"del">​X​</span></p>​
// 3번째의 도레미가 맨 앞으로 옮겨짐

▪ 특정 노드 삭제하기 - removeChild( ) 함수와 parentNode 속성

ar firstDel = document.querySelectorAll(".del")[0]    // 첫 번째 요소 X
undefined                                             
var firstP= document.querySelectorAll("p")[0]        // 첫 번째 요소 p       
undefined
firstP.removeChild(firstDel)                         // 첫 번째 p요소에 있는 첫번째 X 삭제 
<span class=​"del">​X​</span>
  • 참가 신청 명단 프로그램 만들기 - 맨 위에 이름 추가하기
nameList.insertBefore(newP,nameList.childNodes[0]);
   // nameList.appendChild(newP);  
   // newP 노드를 nameList 노드의 자식 노드로 연결
  • 참가 신청 명단 프로그램 만들기 - 이름 삭제하기
   var delBttn = document.createElement("span");   // 새 span 요소 만들기
   var delText = document.createTextNode("X");  // 새 텍스트 노드 만들기
   delBttn.setAttribute("class","del"); // 버튼에 class 속성 설정 하기
   delBttn.appendChild(delText);  // 텍스트노드를 button 요소의 자식 요소로 추가하기
   newP.appendChild(delBttn);   // del 버튼을 p 요소의 자식 요소로 추가하기

X 버튼 만들고 연결

userName.value = "";   // 다른 이름을 입력할 수 있도록 텍스트 필드 비우기

var removeBttns = document.querySelectorAll(".del");

    for (var i=0; i<removeBttns.length;i++){
        removeBttns[i].addEventListener("click",function(){
            if(this.parentNode.parentNode)
                this.parentNode.parentNode.removeChild(this.parentNode);
        })
    }

}

💬 하루 되돌아보기
오늘은 문서 객체 모델, DOM 공부..
차근 차근해서 만들어 가는 건 재밌는데 갈수록 어려워지고 이해가 부족해지는 거 같다ㅠㅠ
아무래도 새로운 함수들이 나타나서 그걸 적용하는 걸 무작정 외우지말고 이해하면서
습득해야하는데 쉽지 않구나!
아무래도 다시 복습하고 다음 강으로 넘어 가야겠다!!

profile
성장중인 개발자🫰

0개의 댓글