[DOM]Document Object Model

킹뎡·2022년 10월 16일

DOM?

문서 객체 모델(The Document Object Model)은 HTML 문서의 내용을 트리형태로 구조화하여 웹페이지와 프로그래밍 언어를 연결시켜주는 역할을 한다. 이때 각각의 요소, 속성, 컨텐츠를 표현하는 단위를 노드(node)라고 한다.

DOM 트리에 접근하기

내가 주로 사용할 것만 정리해보기.
getElementById()
querySelector()
querySelectorAll()

DOM제어 명령어

이벤트 삽입

이벤트 타입에는 click, mouseover, mouseout, wheel 등 다양한 옵션이 있다.

const btn = document.querySelector(".btn")

btn.addEventListner('click', function(){
  ~~~})

클래스 제어

const btn = document.querySelector(".btn")

btn.addEventListner('click', function(){
 btn.classList.add("클래스명")})

add, remove, toggle, contains가 있다. toggle 많이 사용할 것 같다!

요소 제어

const btn = document.querySelector(".btn");
const ulList = document.querySelector("ul");

btn.addEventListener('click', function(){
	for(let i=0; i < 5; i++){
		const liChild = document.createElement('li');	<<<요소를 생성해서
		ulList.appendChild(liChild);					<<<ulList에 생성한 요소를 추가해준다!	
	}
})
// parentElement.insertBefore(target, location); target요소를 parentElement의 자식인 location 위치 앞으로 이동합니다.

var span = document.createElement("span");
var sibling = document.getElementById("childElement");
var parentDiv = document.getElementById("parentElement");
parentDiv.insertBefore(span, sibling);

JS 문자열을 사용해 element, text 노드를 생성 및 추가하기

const myBtn = document.querySelector("button");
const myP = document.querySelector("p");
const myInput = document.querySelector("input");

myBtn.addEventListener('click', function(){
	myP.textContent = myInput.value;
});

// input 요소에 'input' 이벤트를 연결하면 실시간으로 값이 반영되게 만들 수도 있습니다.
myInput.addEventListener('input', ()=>{
  myP.textContent = myInput.value;
});

myP.innerHTML = "<strong>I'm Strong!!</strong>";
myP.outerHTML = "<div></div>";

// innerHTML 은 요소(element) 내에 포함된 HTML 마크업을 가져오거나 설정합니다.
// innerText 속성은 요소의 렌더링된 텍스트 콘텐츠를 나타냅니다. (렌더링된에 주목하세요. innerText는 "사람이 읽을 수 있는" 요소만 처리합니다.)
// textContent 속성은 노드의 텍스트 콘텐츠를 표현합니다.

더 인접한 곳으로 정밀하게 배치하기

실습 후 필요시 작성 예정

DOM 안에서 노드 탐색하기

console.log(container.firstElementChild);  // 첫번째 자식을 찾습니다.
console.log(container.lastElementChild);   // 마지막 자식을 찾습니다.
console.log(container.nextElementSibling); // 다음 형제요소를 찾습니다.
console.log(container.previousSibling);    // 이전 형제노드를 찾습니다.
console.log(container.children);           // 모든 직계자식을 찾습니다.
console.log(container.parentElement);      // 부모 요소를 찾습니다.
> 실습 후 필요시 추가 작성 예정
profile
무럭무럭 자라기

0개의 댓글