jineecode
DOM 스크립트 본문
1. document.getEelementById('')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
</style>
<script>
var title = document.getElementById("main-title");
console.log(title);
</script>
</head>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<article class="">
<header class="main-header">header</header>
<section>
<header>s header</header>
</section>
section 1
<section>
<header>s header</header>
section 2
</section>
</article>
</body>
</html>
<script>
var title = document.getElementById("main-title");
console.log(title);
</script>
결과: null
1-1 window.onload=f()
<script>
window.onload = function () {
var title = document.getElementById("main-title");
console.log(title);
};
</script>
결과: <h1 id="main-title">DOM (Document object model)</h1>
1-2. window.addEventListener(' ', f( ){ });
<script>
window.addEventListener("load", function () {
var title = document.getElementById("main-title");
console.log(title);
});
</script>
결과: <h1 id="main-title">DOM (Document object model)</h1>
*addEventListener의 첫번째 매개변수가 "DOMContentLoaded" 일 경우, DOM의 컨텐트만 로드될 때까지 기다림.
*jquery의 $(document).ready(function( ){ }) 와 같다. - 앞으로 제이쿼리에서 지원 안 함
$(function(){ });를 권장
전역객체가 필요한 명령어는 script를 body 바로 위에 놓으면 써줄 필요 없다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
</style>
</head>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<article class="">
<header class="main-header">header</header>
<section>
<header>s header</header>
</section>
section 1
<section>
<header>s header</header>
section 2
</section>
</article>
<script>
var title = document.getElementById("main-title");
console.log(title);
</script>
</body>
</html>
2. getElementsByTagName
<body>
<h1 id="main-title">
<span>hello</span>
DOM (Document object model)
</h1>
<article>
<header class="main-header">header</header>
<section>
<header>s header</header>
</section>
section 1
<section>
<header>s header</header>
section 2
</section>
</article>
<script>
var title = document.getElementById("main-title");
var titleSpan = title.getElementsByTagName("span");
console.log(titleSpan);
</script>
</body>
</html>
결과:
var title = document.getElementById("main-title");
var titleSpan = title.getElementsByTagName("span");
console.log(titleSpan[0]);
결과: <span>hello</span>
getElementsByTagName 와 getElementById의 차이 ById 는 Id는 고유하기 때문에 단수이지만,
ByTagName은 Tag는 여럿 쓸 수 있으므로 복수로 쓰임.
즉, 배열처럼 인덱스를 정해주어서 호출해야 함.
<body>
<h1 id="main-title">
<span>hello 0</span>
<span>hello 1</span>
<span>hello 2</span>
DOM (Document object model)
</h1>
<article>
<header class="main-header">header</header>
<section>
<header>s header</header>
</section>
section 1
<section>
<header>s header</header>
section 2
</section>
</article>
<script>
var title = document.getElementById("main-title");
var titleSpan = title.getElementsByTagName("span");
console.log(titleSpan[0]);
</script>
</body>
결과: <span>hello 0</span>
3. queryselector(All)
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
img {
width: 50px;
height: 50px;
}
.ilbuni {
display: inline;
list-style: none;
}
</style>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelector("#main-title");
console.log(title);
</script>
</body>
</html>
var title = document.querySelector("#main-title");
document.querySelector(): css선택자처럼 선택자를 ()안에 넣는다.
결과: <h1 id="main-title">DOM (Document object model)</h1>
*jquery에서: document.querySelector = $
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelector(".ilbuni");
console.log(title);
</script>
</body>
querySelector는 객체가 여러 개이더라도 호출 시 처음 하나만 가져온다.
결과:
여러 개를 가지고 오고 싶을 때 querySelectorAll을 쓴다. (이때 배열처럼 나온다.)
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelectorAll(".ilbuni");
console.log(title);
</script>
</body>
결과:
특정 하나를 지정하고 싶은 경우 배열처럼 선택해서 가져온다.
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelectorAll(".ilbuni");
console.log(title[1]);
</script>
</body>
특정 하나에 테두리 넣어보기
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelectorAll(".ilbuni");
title[1].style.border = "1px solid black";
</script>
</body>
모든 이미지에 테두리 넣기(반복문 사용)
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var title = document.querySelectorAll(".ilbuni");
for (let i = 0; i < title.length; i++) {
title[i].style.border = "1px solid black";
}
</script>
</body>
4. getAttribute
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
console.log(link);
</script>
</body>
콘솔 확인 :
a가 아닌 a에 담긴 링크를 가져오고 싶다면?
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
console.log(link.getAttribute("href"));
</script>
</body>
변수명 link가 가지고 있는 객체의 메소드(getAttribute) 문자열로 값을 가져오길 원하는 속성(이 경우 href)을 써준다.
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
console.log(link.getAttribute("class"));
</script>
</body>
console.log(link.getAttribute("class"));
이 경우엔 어떻게 찍힐까?
class를 담고 있는 link-google이 찍힌다.
5. setAttribute
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
console.log(link.getAttribute("href"));
link.setAttribute("href", "http://studio.com");
//link.setAttribute("선택자", "바꿀링크");
console.log(link.getAttribute("href"));
//확인
</script>
</body>
결과:
setAttribute은 리턴값이 없으며 정의되지 않으므로 콘솔을 찍어봐도 undefined가 뜬다
6. link.className
js로 원하는 엘리먼트에 pink 넣어보기.
바닐라 확인
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
img {
width: 50px;
height: 50px;
}
.ilbuni {
display: inline;
list-style: none;
}
.special {
background: pink;
}
</style>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
link.className = "special";
</script>
</body>
link.className = "special";
데려온 link애 className special을 잡아줘서 넣어보자.
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
img {
width: 50px;
height: 50px;
}
.ilbuni {
display: inline;
list-style: none;
}
.link-google {
color: red;
}
.special {
background: pink;
}
</style>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
//link.className = "special";
</script>
</body>
결과:
<style>
body {
font-size: 3rem;
}
h1 {
background: #fff000;
}
img {
width: 50px;
height: 50px;
}
.ilbuni {
display: inline;
list-style: none;
}
.link-google {
color: red;
}
.special {
background: pink;
}
</style>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
link.className = "special";
</script>
</body>
결과:
link.className = "special";
를 썼을 경우,
class 가 'link-google'에서 'special'로 바꿔치기 된 것을 확인할 수 있다.
class를 모두 다 적용시키기 위해서는
link.className = "special link-google";
이렇게 모두 살려줄 필요가 있다.
이 방법은 너무 번거롭다.
7. link.classList.add('추가하고 싶은 클래스명')
add가 메서드이므로 괄호 호출.
8. link.classList.remove('삭제하고 싶은 클래스')
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul>
<li class="ilbuni">
<img src="bear.jpg" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
<li class="ilbuni">
<img src="bear.jpg" />
</li>
</ul>
<script>
var link = document.querySelector(".ilbuni a");
// link.className = "special";
link.classList.add("special");
setTimeout(function () {
link.classList.remove("link-google");
}, 2000);
</script>
</body>
9. link.classList.contains('가지고 있는 class')
contains는 불리언 값을 리턴한다.
가지고 있는 class를 link가 가지고 있으면 true 아니면 false
<script>
var link = document.querySelector(".ilbuni a");
// link.className = "special";
link.classList.add("special");
setTimeout(function () {
link.classList.remove("link-google");
}, 2000);
console.log(link.classList.contains("special"));
</script>
결과: true
10. document.createElement('li'); / appendChild
*li 태그에 자바스크립트로 li 끼워넣기
1. 일단 없는 것을 만들어서 조립해야 하므로, 만드는 것부터 하자.
<script>
var listElem = document.createElement("li");
console.log(listElem);
</script>
결과: <li></li>
물론 괄호 안에 h1을 넣으면 결과가 <h1></h1> 가 나온다.
2. 만든 element를 조립한다.
<script>
var listElem = document.createElement("li");
listElem.innerHTML = '<span>일분이</span>';
console.log(listElem);
</script>
결과:
innerHTML은 함수가 아닌, 속성임
조립을 할 땐 부모가 넣어줘야한다.
li의 부모는 ul이므로 ul을 불러와서 조립
<body>
<body>
<h1 id="main-title">DOM (Document object model)</h1>
<ul class="ilbuni-mom">
<li class="ilbuni">
<img src="#" />
<a class="link-google" href="http:google.com">google</a>
</li>
<li class="ilbuni">
<img src="#" />
</li>
<li class="ilbuni">
<img src="#" />
</li>
</ul>
<script>
var ilbuniMom = document.querySelector('.ilbuni-mom');
var listElem = document.createElement("li");
listElem.innerHTML = '<span>일분이</span>';
// 부모가 해줘야함
ilbuniMom.appendChild(listElem);
</script>
</body>
'JS' 카테고리의 다른 글
지역 선택 JS로 제어하기 (2) | 2021.02.26 |
---|---|
이벤트 위임 (0) | 2021.02.25 |
깨알 기초 지식 모음 (0) | 2021.02.14 |
끝말잇기 만들기 (0) | 2020.12.08 |
EVENT (0) | 2020.11.26 |