1.Docunebt Object Model(문서 객체 모델)
2.HTML 구성 요소(HTMLCollection/HTMLElement, NodeList/Node)를 객체(Object)로 저장하고 처리할 수 있는 방식이다.
3.HTML 구성 요소 (HTMLCollection/HTMLElement, NodeList/Node) 알아내기
1) id 속성으로 알아내기
var 변수 = document.getElementById('아이디')
2) class 속성으로 알아내기
var 배열 = document.getElementsByClassName('클래스')
3) tag 이름으로 알아내기
var 배열 = document.getElementsByTagName('태그')
4) 선택자로 알아내기
var 변수 = document.querySelector('선택자')
5) 선택자로 알아내기
var 배열 = document.querySelectorAll('선택자')
4. 반드시 HTML 구성 요소(HTMLCollection/HTMLElement, NodeList/Node)를 먼저 만들어야 한다. <script> 태그는 나중에 만든다.
예시 html
<div class="wrap">
<div id="box1" class="primary_box">box1</div>
<div id="box2" class="primary_box">box2</div>
<div id="box3" class="primary_box">box3</div>
</div>
var box1 = document.getElementById('box1');
console.log(box1);
var box2 = document.getElementById('box2');
console.log(box2);
var box3 = document.getElementById('box3');
console.log(box3);
var primary_box = document.getElementsByClassName('primary_box');
console.log(primary_box);
var div = document.getElementsByTagName('div');
console.log(div);
// 선택자를 이용해 id="box1", id="box2", id="box3" 알아내기
var box1 = document.querySelector('#box1');
console.log(box1);
var box2 = document.querySelector('#box2');
console.log(box2);
var box3 = document.querySelector('#box3');
console.log(box3);
// 선택자를 이용해 class="primary_box" 알아내기
var primary_box = document.querySelectorAll('.wrap > .primary_box');
console.log(primary_box);
태그 속성 변경예시
<!-- 태그 내부 텍스트 -->
<p id="p1">Hello World</p>
<script>
var p1=document.getElementById('p1');
console.log(p1.textContent);
p1.textContent='안녕하세요';
p1.textContent+=' 반갑습니다';
</script>
<!-- 태그 내부 요소 -->
<p id="p2">Hello World</p>
<script>
var p2=document.getElementById('p2');
console.log(p2.innerHTML);
p2.innerHTML='<em>안녕하세요</em>'
p2.innerHTML+='<mark>반갑습니다</mark>'
</script>
<!-- 태그 속성 -->
<p id="p3">
<img src="../../assets/images/flower1.jpg" width="384px">
</p>
var img=document.querySelector('#p3 > img');
console.log(img.getAttribute('src'));
img.setAttribute('src','../../assets/images/flower2.jpg');
img.setAttribute('width','384px');
img.removeAttribute('src');
img.removeAttribute('width');
</script>
예시)
예시)
| attribute | property
------------------------------------------------------------------
id ="box" | id="box" | id:box
class="p" | class="p" | className: p
checked="checked" | checked="checked" | checked: true
프로퍼티 호출 방식1
console.log('type',male.type);
console.log('name',male.name);
console.log('value',male.value);
console.log('id',male.id);
console.log('class',male.className);// js로 호출되어 저장될 때는 className
console.log('checked',male.checked);
프로퍼티 호출 방식2
var female=document.getElementById('female');
console.log('type',female['type']);
console.log('name',female['name']);
console.log('value',female['value']);
console.log('id',female['id']);
console.log('class',female['className']);
console.log('checked',female['checked']);