16. 문서 객체 모델 (DOM, Document Object Model) : DOM 트리
문서 노드 : 전체 문서를 가르키는 Document 객체
HTML 요소 노드 : HTML 요소를 가르키는 객체
텍스트 노드 : 텍스트를 가르키는 객체
# 노드 객체 가져오는 메서드
document.getElementById(id값) : id 속성값으로 노드 가져오기
document.getElementsByTageName(name) : 태그명으로 노드 찾기 (배열로 리턴)
document.getElementsbyClassName(name) : class 속성값으로 노드 가져오기 (배열로 리턴)
document.querySelector(css선택자) : css 선택자로 노드 찾기 (첫번째 찾은 요소만 리턴)
document.querySelectorAll(css선택자) : css 선택자로 노드 찾기 (모든요소 배열로 리턴)
<h1>hello</h1>
# 찾은 HTML 요소 확인/수정
요소.innerText = '대치할 새로운 텍스트' : 요소 안의 내용 확인/ 수정 (태그 미포함)
요소.innerHTML = '새로운 HTML 내용' : 요소 안의 내용 확인/ 수정 (태그 포함)
요소.attribute = 새값 : 요소의 속성값 수정
요소.setAttribute(속성명, 값) : 요소의 속성값 메서드로 설정
# HTML 요소 생성/추가
document.creatElement(태그명) : HTML 태그 생성
document.appendChild(요소) : 요소 추가하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="first"> div 1
<div>1-1</div>
<div>1-2</div>
<div>1-3</div>
<div class = "test"> test div</div>
</div>
<div id ="second"> div 2</div>
<div id ="third"> div 3</div>
<script>
let elem0 = document.getElementsByTagName('div'); // 태그 div 로된 모든 노드 출력
let elem1 = document.getElementsByClassName('first'); // 클래스 first 로된 노드 출력
console.log(elem0); // HTMLCollection(7) [div.first, div, div, div, div.test, div#second, div#third, second: div#second, third: div#third]
console.log(elem1); // HTMLCollection [div.first]
let elem2 = document.getElementById('second');
console.log(elem2);
let elem3 = document.querySelector('div.test');
console.log(elem3);
let elem4 = document.querySelectorAll('div');
console.log(elem4); //NodeList(7) [div.first, div, div, div, div.test, div#second, div#third]
for(let i = 0; i<elem4.length; i++){
console.log(elem4[i].innerText); // 글자만 가져오기
}
for(let i = 0; i<elem4.length; i++){
console.log(elem4[i].innerHTML); // html 다가져오기
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width : 100px;
height: 100px;
text-align: center;
}
</style>
</head>
<body>
<h1>hello</h1>
<script> // 16번
const newTag = document.createElement('div'); // div태그 스크립트로 생성
newTag.innerText = 'JavaScript';
newTag.setAttribute("class","box");
newTag.style.background = "red";
newTag.style.color = "white";
document.body.appendChild(newTag);
</script>
</body>
</html>
'P-Language > [Javascript]' 카테고리의 다른 글
[JS] submit 버튼 눌렀을때 alert YES / NO 띄우기 (0) | 2022.07.29 |
---|---|
[Javascript] 17 - addEventListener() 이벤트 등록 (0) | 2022.06.09 |
[Javascript] 15 (2) - 브라우저 객체 모델 (BOM, Browser Object Model) (history, navigator object) (0) | 2022.06.09 |
[Javascript] 15 (1) - 브라우저 객체 모델 (BOM, Browser Object Model) (window, screen, location object) (0) | 2022.06.09 |
[Javascript] 14 - 내장 객체 (Built-in Object) (0) | 2022.06.09 |