// id로 선택
// js
document.getElementById("id값");
// jQuery로 변환
$("#id값")
// js
let h1 = document.getElementById("id값");
// jQuery로 변환
let h1 = $("#id값")
// 클래스로 선택
$.(".클래스이름");
// 태그로 선택
$("태그명");
// form 태그에 지정된 name 속성을 통하여 form 객체를 획득
let myform = document.form1;
// form 태그 객체는 자신이 포함한 하위 태그에 객체를 갖는다.
// name 속성을 통하여 이 하위 객체에 접근할 수 있다.
let user_name = myform.user_name;
// 중간 과정 생략하고 직접 적근하는 방법
let user_name2 = document.form1.user_name;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="alert" onclick="alert(window.location);">
<!--
onlick : 사용자가 버튼을 클릭했을 '때' 실행
event target : 이벤트가 일어날 객체를 의미한다. 여기서는 버튼 태그에 대한 객체가 타겟
event type : 이벤트의 종류를 의미한다. click이 이벤트 타입
event handler : 이벤트가 발생했을 때 동작하는 코드를 의미한다.
여기서는 alert(window.location)이 해당된다.
-->
</body>
</html>
[출력 결과]
alert버튼을 클릭하면 window.location 정보를 담은 alert 창이 뜬다.
1-1. 인라인(inline) 방식
인라인 방식은 이벤트를 이벤트 대상의 태그 속성으로 지정하는 것
[예제 코드]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>10 + 50 = <span id="question"> ? </span> </h1>
<input type="button" value="결과보기"
onclick="printResult();">
<script>
// 결과보기 버튼 클릭시, 10 + 50의 결과 값을 '?' 안에 넣어줄것
function printResult() {
let result = sum(10, 50);
// id로 접근
let mytag = document.getElementById("question");
mytag.innerHTML = result;
}
function sum(x, y){
return x + y;
}
</script>
</body>
</html>
[출력 결과]
1-2. 자기 자신 참조하기
방법 1 : getElement~로 참조하기. 따로 지정될 id나 class 등을 명시해야 해서 불편하다.
방법2 : this로 참조하기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 자기 자신을 참조하는 불편한 방법 -->
<input type="button" id="target"
onclick="alert('event_1 : ' + document.getElementById('target').value);"
value="button"/>
<!-- this를 통해서 간편하게 참조하는 방식 -->
<!-- 이벤트가 발생한 대상을 필요로 하는 경우, this를 통해서 참조할 수 있다 -->
<input type="button"
onclick="alert('event_1 : ' + this.value);"
value="button">
</body>
</html>
[출력 결과]
▶ 두 개의 버튼 모두 방법은 다르지만 동일한 결과를 출력한다.
1-3. 프로퍼티 리스너
이벤트 대상에 해당하는 객체의 프로퍼티로 이벤트를 등록하는 방식이다.
인라인 방식에 비해서 HTML과 Javascript를 분리할 수 있다는 점에서 선호되는 방식이지만, 뒤에서 배울 addEventListener 방식을 추천한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="target" value="button" />
<script>
let t = document.getElementById('target');
t.onclick = function(){
alert('Hello world');
}
</script>
</body>
</html>
[출력 결과]
function()에 보통 파라미터로 event를 넣는다.
이것을 console.log(event)로 출력해 봄으로써 이벤트가 발생할 때의 정보 확인이 가능하다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="target" value="button" />
<script>
let t = document.getElementById('target');
t.onclick = function(event){
alert('Hello world : ');
console.log(event);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<!-- onload : 페이지 최초 로딩시, authNo() 함수를 호출 -->
<body onload="authNo()">
<!--
문제. 0~9 사이의 랜덤 5자리 인증번호를 id값이 "auth"인 요소에서 출력
document.getElementById("auth").innerHTML = 랜덤숫자;
-->
<p>
고객님의 인증번호는 <strong id ="auth">00000</strong>입니다.
</p>
<input type="button" value="인증번호 새로 받기" onclick="refresh();"/>
<script>
function refresh(){
// location 객체 안에 포함된 reload()함수는 현재 페이지를 새로고침한다.
location.reload();
}
// 두 수 사이의 랜덤값을 리턴하는 함수
function random(n1, n2){
return parseInt(Math.random()*(n2 - n1 + 1)) + n1;
}
// 5가지 인증번호 return해주는 함수
function authNo(){
let value = "";
for(let i = 0 ; i<5; i++){
value += random(0,9);
}
document.getElementById("auth").innerHTML = value;
}
</script>
</body>
</html>
[출력 결과]
▶ 페이지 최초 로딩시 authNo() 함수를 실행한다.
▶ '인증번호 새로 받기' 버튼을 클릭하면 refresh() 함수를 실행하여 페이지를 새로고침한다.
▶ 페이지가 새로고침되면서 다시 authNo() 함수가 실행된다.
1-3.history 객체
history 객체는 브라우저의 "뒤로", "앞으로" 버튼의 기능을 수행하는 객체로써, back() 함수와 forward() 함수를 내장하고 있다.
이전 페이지로 이동하기 : history.back();
다음 페이지로 이동하기 : history.forward();
[예제 코드]
- window5.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>History 객체</h1>
<a href="history.html">페이지 이동</a><br>
<a href="#" onclick="history.forward(); return false;">
앞 페이지로 이동
</a>
</body>
</html>
- history.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>History 객체</h1>
<a href="#" onclick="history.back(); return false;">
이전 페이지로 이동
</a>
</body>
</html>
[출력 결과]
▶ 페이지 이동 클릭 시 <a href>로 지정한 history.html로 페이지가 이동된다.
▶ 이전 페이지로 이동 클릭 시 history.back() 함수가 실행되어 window5.html로 돌아온다.
▶ window5.html에서 앞페이지로 이동 클릭 시 history.forward() 함수가 실행되어 앞페이지(history.html)로 돌아간다.
1-4. navigator
브라우저의 정보를 조회하는 내장 객체
하나의 웹서비스로 다양한 브라우저를 지원할 수 있도록 처리하기 위한 기본이 되는 정보를 추출할 수 있다.
navigator.appName : 브라우저 이름
navigator.appCodeName : 브라우저 코드명
navigator.platform : 플랫폼 정보
navigator.appVersion : 브라우저 정보
navigator.userAgent : 사용자 정보
2. document
2-1. document.getElementsByTagName
문서 내에서 특정 태그에 해당되는 객체를 찾는 방법은 여러가지가 있다.
인자로 전달된 태그명에 해당하는 객체들을 찾아서 그 리스트를 유사배열에 담아서 반환한다.
[예제 코드 1]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<script>
let list = document.getElementsByTagName("li");
for(let i = 0; i < list.length; i++){
list[i].style.color = 'tomato';
}
</script>
</body>
</html>
[출력 결과 1]
[예제 코드 2]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
<script>
let ul = document.getElementsByTagName('ul')[0];
let lis = ul.getElementsByTagName('li');
for(let i = 0; i < lis.length; i++){
lis[i].style.color = 'tomato';
}
</script>
</body>
</html>
▶ ul 태그에서도 1depth 더 들어가 li 태그 지정 후 스타일 준 형태
[출력 결과 2]
2-2. document.getElementsByClassName
class 속성의 값을 기준으로 객체를 조회
[예제 코드]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ul>
<li>HTML</li>
<li class = "active">CSS</li>
<li class = "active">JavaScript</li>
</ul>
<script>
let lis = document.getElementsByClassName('active');
for (let i = 0; i < lis.length; i++) {
lis[i].style.color = 'powderblue';
}
</script>
</body>
</html>
[출력 결과]
2-3. document.getElementById
id 값을 기준으로 객체를 조회한다. 성능면에서 가장 우수
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ul>
<li>HTML</li>
<li id = "active">CSS</li>
<li>JavaScript</li>
</ul>
<script type="text/javascript">
let li = document.getElementById('active');
li.style.color = 'tomato';
</script>
</body>
</html>
let url = "http://www.naver.com";
document.write("<p>문자열 : " + url + "</p>");
let len = url.length;
document.write("<p>문자열의 길이 : " + len + "</p>");
let position = url.indexOf("/");
document.write("<p>'/' 가 처음 나타나는 위치 : " + position + "</p>");
let up = url.toUpperCase();
document.write("<p>모든 글자 대문자 : " + up + "</p>");
let down = url.toLowerCase();
document.write("<p>모든 글자 소문자 : " + down + "</p>");
[출력 결과]
2. HTML 안에서 JS 사용
2-1. Inline방식
태그에 직접 자바스크립트를 기술하는 방식.
장점은 태그에 연관된 스크립트가 분명하게 드러난다는 점이다.
하지만 정보(HTML)와 제어(Javascript)가 섞여있기 때문에 정보로서의 가치가 떨어진다.