728x90
반응형
셀렉터 ( 선택자 )
document.getElementsByTagName(태그명)
-> 복수의 HTML Tag를 선택하여 객체를 반환한다.
document.getElementById(아이디명)
-> 1개의 ID에 대한 값들을 가져 온다
document.getElementsByClassName(클래스명)
-> 복수의 Class의 객체(배열) 모두를 가져 온다
document.querySelector(선택자)
-> 단수개의 값만을 가져온다. 만약 여러개가 있다면 처음 하나만 가져 온다.
document.querySelectorAll(선택자)
-> 복수의 값을 배열로 가져 온다.
- 버튼 클릭하면 id, class 명에 따라서 색상 변경
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>선택자</title>
</head>
<body>
<script type="text/javascript">
function func(){
document.getElementById('test').style.backgroundColor="red";
var elems=document.getElementsByClassName('test2');
for(var i =0;i<elems.length;i++){
elems[i].style.backgroundColor='orange';
}
}
</script>
<button type="button" onclick="func()">색깔 바꾸기</button>
<ul>
<li>1</li>
<li class="test2">2</li>
<li id="test">3</li>
<li class="test2">4</li>
</ul>
</body>
</html>
|
cs |
- querySelectorAll 사용하여 버튼 클릭시 무지개 색상 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
function func(){
var color=['red','orange','yellow','lightgreen','aqua','blue','purple'];
var elems=document.querySelectorAll('li');
for(var i=0;i<elems.length;i++){
elems[i].style.backgroundColor=color[i];
}
}
</script>
<button onclick="func()">무지개</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</body>
</html>
|
cs |
콜백함수
CallBack 함수란 이름 그대로 나중에 호출되는 함수를 말한다.
콜백함수라고 해서 그 자체로 특별한 선언이나 문법적 특징을 가지고 있지는 않다.
콜백함수도 일반적인 자바스크립트 함수일 뿐이다.
콜백 함수는 코드를 통해 명시적으로 호출하는 함수가 아니라, 개발자는 단지 함수를 동록하기만 하고, 어떤 이벤트가 발생했거나 특정 시점에 도달했을 때 시스템에서 호출하는 함수를 말한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>콜백함수 형식</title>
<style type="text/css">
.box{
width: 100px;
height: 100px;
background-color: pink;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
document.querySelector('.box').onclick=function(){
this.style.backgroundColor='lightgreen';
}
</script>
</body>
</html>
|
cs |
클릭 전
클릭 후
728x90
반응형
'JavaScript' 카테고리의 다른 글
[JavaScript] window객체, history, form (0) | 2022.07.28 |
---|---|
[JavaScript] 이벤트 리스너 (0) | 2022.07.28 |
[JavaScript] Eclipse에 jQuery 라이브러리 셋팅법 (0) | 2022.07.27 |
[JavaScript] 마우스, 키보드 이벤트 (0) | 2022.07.27 |
[JavaScript] 랜덤, Math함수를 사용하여 UpDown 게임 만들기 (0) | 2022.07.26 |