NodeList : node를 index로 가져오는 방법

DOM이 아니다.

value값을 가져올 수 있는 방법 중 하나이다.

 

사용목적 : id나 class 추가를 못할 때 수정해야 할 경우에 사용한다.

 

예시

<p>hello</p>
<p>world</p>
<p>I can do it</p>
<p>Never change my mind</p>

<button type="button" onclick="listfunc()">nodelist</button>

<script type="text/javascript">
function listfunc() {
	let nodelist = document.getElementsByTagName('p');

	nodelist[3].innerHTML = "나는 문제없어"; // 3번지 수정
	
	for (var i = 0; i < nodelist.length; i++) { 
		nodelist[i].style.backgroundColor = '#ff0000';
	}
}
</script>

 

설명

getElementsByTagName(태그) : index로 값을 넘겨받는다.

hello world I can do it Never change my mind
0번지 1번지 2번지 3번지

전체 수정을 하고 싶은 경우 for문을 사용한다.

 

실행화면

Insert title here

hello

world

I can do it

Never change my mind

버튼 클릭 시 수정된 걸 확인할 수 있다.

DOM(Document Object Model) : 문서 객체 모델

각 tag를 접근하기 위한 object
그 object를 접근하기 위한 함수들의 모음

 

Document : 문서 안에 tag에 접근하도록 만들어진 객체(내장 object)

 

자주 사용되는 접근 메서드

getElemetById('id명') : id에 접근
getElemetsByClass('class명') : class들에 접근 (배열로 넘겨준다.)
getElemetsByName('name명') : name들에 접근 (배열로 넘겨준다.)
getElemetsByTagName('tag명') : tag들에 접근 (배열로 넘겨준다.)


childNodes : 요소가 포함하고 있는 자식 요소를 찾고 싶을 때 사용한다.

childNodes 사용 예시

<select id="cars"> <!-- 0번지 -->
	<option>Benz</option> <!-- 1,2번지 -->
	<option>BMW</option>
	<option>volvo</option>
</select>
<button type="button" onclick="cars()">선택</button>
<script type="text/javascript">

function cars() {
	let carName = document.getElementById('cars').childNodes; // 배열로 넘어온다.	
	alert(carName[1].text); // Benz
}
</script>    

설명

document.getElementById('cars').childNodes : id=cars인 요소의 번호를 배열로 넘겨받게 된다.

 

cars의 요소번호

<select> <option> </option> <option> </option> <option> </option>
0번지 1번지 2번지 3번지 4번지 5번지 6번지

alert(carName[1].text) : carName의 1번지의 value값을 경고창에 출력하게 된다.


appendChild : 자식 요소의 맨 뒤에 데이터를 추가한다.

appendChild 사용예시

<div id="div1">
	<p id="p1">첫번째 p태그</p>
	<p id="p2">두번째 p태그</p>
</div>

<script type="text/javascript">
function appendfunc() {
	let ptag = document.createElement('p'); // 새로운 <p></p> 추가
	let textNode = document.createTextNode("새로운 p 태그"); 
	
	ptag.id = "newid"; // p tag에 id추가
	ptag.className = "newclass" // p tag에 class추가
	
	ptag.appendChild(textNode) // <p id="newid" class="newclass">새로운 p 태그</p> 완성!
	
	let element = document.getElementById('div1'); // object가져옴
	element.appendChild(ptag); // div태그에 추가된다. p태그말고 테이블 같은걸 많이 추가한다.
}

설명 (태그명,요소명 == 변수명)

createElement(태그) : 새로운 tag를 추가한다.

createTextNode(내용) : tag에 넣을 내용을 추가한다.

태그명.appendChild(내용명) : 새로운 tag 완성! 

요소명.appendChild(태그명) : 요소 안에 새로운 tag를 추가한다. 


insertChild :  자식 요소의 추가할 위치를 선택하여 데이터를 추가한다.

insertChild 사용예시

function insertfunc() {
	let h2tag = document.createElement('h2'); // 모든태그를 추가할 수 있다
	let textNode = document.createTextNode("h2 태그를 추가");
	// id와 class 모두 추가할 수 있다.
	
	h2tag.appendChild(textNode); // <h2>h2 태그를 추가</h2> 완성!
	
	let element = document.getElementById('div1'); 
	//  앞에 붙일 땐 어디 앞에 지정을 해주어야 한다. 추가될 위치를 지정할 수 있다.
	let elementBefore = document.getElementById('p2'); 
	
	element.insertBefore(h2tag, elementBefore) // p1앞에 추가해라
}

설명 (태그명,요소명 == 변수명)

요소명.insertBefore(추가할 태그명, 추가할 위치 태그명) : 추가할 위치 태그명 앞에 추가가 된다.


 

removeChild :  자식 요소를 삭제한다.

function deletefunc() {
	let element = document.getElementById('div1');
	let removeElement = document.getElementById('p2');
	//  id=div1태그 안의 id=p2를 삭제해라
	element.removeChild(removeElement); 
}

설명 (태그명,요소명 == 변수명)

요소명.removeChild. 삭제할 태그명 :  요소 안에 태그를 삭제한다.

 

전체코드 실행화면

Insert title here

첫번째 p태그

두번째 p태그

 

버튼을 클릭하면 추가 삭제가 된다.

 

Insert title here

미술관 및 박물관 링크

 

예제

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>미술관 및 박물관 링크</h1>
<select id="links" onchange="golink()">
	<option>대상을 선택</option>
	<option value="https://sema.seoul.go.kr/">・서울시립미술관</option>
	<option value="https://www.sac.or.kr/">・국립현대미술관</option>
	<option value="https://www.museum.go.kr/">・예술의전당</option>
	<option value="https://museum.seoul.go.kr/">・국립중앙박물관</option>
	<option value="https://museum.seoul.go.kr/">・서울역사박물관</option>
	<option value="https://www.nfm.go.kr/">・국립민속박물관</option>
</select>
<script type="text/javascript">
function golink() {
	// select index 번호 구하기
	let selectIndex = document.getElementById("links").selectedIndex;
	// 선택된 index value값 가져오기
	let url = document.getElementById("links").options[selectIndex].value;
	if(selectIndex != 0){
		location.href = url;
	}
}
</script>
</body>
</html>

 

설명

 option을 선택할 때 onchange 이벤트가 발생하여 golink함수로 이동한다.

 select태그의 id명으로 option의 index번호를 구한다.

 index번호로 option의 value값(링크)을 구한다.

 location.href 사용하여 클릭 링크로 이동한다.

 

 

onload : 이벤트 객체가 로드될 때 이벤트가 발생한다.

 

신문 자동 스크롤 내리기 예시

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body onload="viewScroll()">
<pre> 신문내용을 넣으세요. </pre>
<script type="text/javascript">
let posY = 0;
function viewScroll(){
	window.scroll(0, posY);
    
	posY = posY + 2;
	if(posY == 300) posY = 0;   // 300이 되면 초기화(맨 위로 올라간다.) 
    						 // 화면이 꽉 차면 움직이지 않는다.
	
	setTimeout( "viewScroll()", 100); // 0.1초마다
}
</script>
</body>
</html>

 

설명

 pre태그 안에 신문 내용을 넣고, 코드를 실행하면 0.1초마다 스크롤이 내려간다.

 body태그가 실행될 때  onload 이벤트가 발생하여 viewScroll함수를 실행한다.

 

 

함수설명

window.scroll(x-coord, y-coord) : 대상 요소의 스크롤바가 이동할 때마다 이벤트를 발생시키거나 강제로 스크롤 이벤트를 발생시키는데 사용(x = 가로, y = 세로)

setTimeout("함수명()", 지연시간(ms)) : 시간 지연 함수, 지연시간 후 실행시킬 때 사용

 

 

※ 실행화면을 올리고 싶었는데.. 같은 코드를 실행시 티스토리가 스크롤링이 되어 올리지 못했다...

onkeydown :  키보드에서 키를 눌렀을 때 이벤트 발생

 

온키다운 키코드 :

 

예제

온키다운 키코드 : <input type="text" name="title1" size="5">
<script type="text/javascript">
document.getElementsByName("title1")[0].onkeydown = function (event) {
	alert("keycode : " + event.keyCode) // event 매개변수로 넘어온다. 
}
</script>

 

설명

 text란에 값을 넣어주면 keyCode의 값을 반환하여 경고창에 출력된다.


onkeypress : 키보드에서 키를 눌렀을 때 이벤트 발생

 

온키프레스 키코드 :

 

예제

온키프레스 키코드 : <input type="text" name="title2" size="5">
<script type="text/javascript">
document.getElementsByName("title2")[0].onkeypress = function (event) {
	alert("keycode : " + event.keyCode) // event 매개변수로 넘어온다. 
}
</script>

 

설명

 text란에 값을 넣어주면 ascii 코드의 값을 반환하여 경고창에 출력된다.

mouse이벤트

onmousedown : 마우스 포인터가 요소 안으로 들어올 때 (마우스 클릭 시)

onmouseup : 마우스 버튼을 올릴 때(클릭한 걸 뗄 때)

onmouseover : 마우스 포인터가 요소 안으로 들어올 때 (마우스 올려놨을 때)

onmouseout : 마우스 포인터가 요소 밖으로 나갈 때 (마우스 뜻을 때)


 

Insert title here

 

예제

<input type="image" src="images/san0.gif" 
					onmousedown="mouseDown(this)" 
					onmouseup="mouseUp(this)"
					onmouseover="mouseOver(this)"
					onmouseout="mouseOut(this)">
					
<script type="text/javascript">
function mouseDown(obj) { // 마우스 포인터가 요소안으로 들어올 때 (마우스 클릭시)
	obj.src = "images/san1.gif";
}
function mouseUp(obj) { // 마우스 버튼을 올릴 때(클릭한 걸 뗄 때)
	obj.src = "images/san0.gif";
}
function mouseOver(obj){ // 마우스 포인터가 요소안으로 들어올 때 (마우스 올려 놨을 때)
	obj.src = "images/san2.gif";
}
function mouseOut(obj){ // 마우스 포인터가 요소 밖으로 나갈 때 (마우스 땟을때)
	obj.src = "images/san0.gif";
}
</script>

 

설명

 input type을 img로 묶어 이벤트 발생 시마다 함수를 지정한다.

 이벤트가 발생할 경우 지정 함수로 이동하여 이미지를 바꿔준다.


Insert title here

onmouseover, onmouseout 사용예제

<a href="#" onmouseover="document.box.src='images/surprise.gif'" 
			onmouseout="document.box.src='images/box.gif'">
			<img alt="" src="images/box.gif" name="box">

 

설명

 마우스를 그림(요소) 안으로 올리면 onmouseover 이벤트가 발생하여 그림이 바뀌고

 마우스가 그림 밖으로 나가면 onmouseout 이벤트가 발생하여 원복이 된다.

onblur :  포커스를 잃었을 때 실행된다.


Insert title here 나이 :

예제

나이 : <input type="text" onblur="inRegNum()" size="10" maxlength="2">세<br><br>
<script type="text/javascript">
function inRegNum() {
	alert('onblur 실행됨'); // 포커스가 딴 곳으로 가면 실행됨.
}

 

설명

 포커스 영역은 text영역이고 text영역을 벗어날 때 이벤트가 발생합니다.


onchage : 포커스가 바뀌었을 때 실행된다.

 

 

예제

<select id="sel" onchange="chageVal()">
 	<option value="apple">사과</option>
 	<option value="pear">배</option>
 	<option value="banana">바나나</option>
</select>

<script type="text/javascript">
function chageVal() {
	let val = document.getElementById("sel").value;
	alert(val); // 선택한 value값이 출력된다.
}
</script>

 

설명

 포커스 영역은 option안이고, option 클릭이 바뀔 때마다 이벤트가 발생합니다.

 

link :  이동시키는 것

앵커 태그 : href

폼 태그 : action

자바스크립트 : location.href


 

 

NewFile.jsp로 이동

 

 

a href 예제

<a href="NewFile.jsp?name=홍길동&age=24">NewFile.jsp로 이동</a> 

 

설명

name=홍길동&age=24 파라미터 값으로 '홍길동'과 '24'를 NewFile.jsp로 넘겨준다.

 

NewFile.jsp 예제

<% // 스크립트 립 : 자바의 영역, DB와 연동가능
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
out.println("이름 : " + name + "<br>");
out.println("나이 : " + age +  "<br>");
%>

 

 

설명

request.getParameter : 파라미터명으로 접근하여 데이터를 넘겨받는다.

파라미터명이 name이라면 '홍길동'을 넘겨받게 된다.

 

링크 클릭 후 실행화면


이름 :
나이 :

 

form action 예제

<form action="NewFile.jsp">
이름 : <input type="text" name="name">
<br>
나이 : <input type="text" name="age">
<br>
<input type="submit" value="이동">
</form>

 

설명 

form태그는 a태그와 달리 값을 입력받을 수 있다.  form 영역에 input 태그를 묶는다. 

NewFile.jsp에 name명으로 접근하여 값을 넘겨준다.

 


Insert title here 이름 :
나이 :

 

location.href 예제

이름 : <input type="text" id="name">
<br>
나이 : <input type="text" id="age">
<br>
<button type="button" onclick="move()">이동</button>

<script type="text/javascript">
function move() {
	let name = document.getElementById("name").value;
	let age = document.getElementById("age").value;
	// 스페이스바 주의 null값 우려
	location.href ="NewFile.jsp?name="+ name +"&age="+ age; 
}	
</script>

 

설명

button  클릭 시 move() 함수로 이동하여 text의 입력값을 각 변수에 넣어준다.

a href와 비슷한 방식으로 location.href에 값을 주어 NewFile.jsp에 접근한다.

 

 

※ 이동을 눌러도 jsp파일이 없어서 실행되지 않습니다..

 

 

라면 타이머



time selected

 

* 티스토리에서 wav파일 접근 경로를 파악하지 못하여 알람은 울리지 않습니다. ㅠㅠ

 

라면 타이머 예제 코드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="" name="frm">
<div align="left">
<strong>라면 타이머</strong>
<br><br>
<!-- id와 name 같은이름 사용가능 -->
<select id="selid" name="selid">
	<option value="180">시간 선택(기본:3분)</option> 
	<option value="300">5분</option>
	<option value="180">3분</option>
	<option value="120">2분</option>
	<option value="60">1분</option>
	<option value="30">30초</option>
</select>

<input type="button" value="Timer Start" onclick="noodle()">
<br><br>

<!-- CSS 묶을 때 많이 사용한다 -->
<span id="countdown">time selected</span>
<br><br>

<button type="button" onclick="window.close()">close</button>

</div>
</form>
<script type="text/javascript">

let index = 0; // 다른 함수에서도 사용하기 위해 
let value = 0;
let time = 0;

function noodle() {
	clearInterval(time); // timer 초기화
	index = document.frm.selid.selectedIndex; // index 번호를 가져온다.
	value = parseInt(document.frm.selid.options[index].value);
	time = setInterval('noodleTimer()', 1000); // 1초마다 noodleTimer()함수 호출
}

function noodleTimer() {
	value = value - 1; // 1씩 빼나가도록 한다.
	// 1초마다 실행
	document.getElementById('countdown').innerHTML = "완료까지 <b>" + value + "</b>초 남았습니다";
	
	if(value == 0){
		clearInterval(time);
		
		let audio = new Audio('AlarmClockBell.wav');
		audio.play();
	}
}

</script>
</body>
</html>

 

함수 설명

clearInterval() : 매개변수로 변수명과 함수명을 받으며 사용 시 매개변수가 종료됩니다.(초기화)

setInterval('함수명', 시간 간격) :  일정한 시간간격으로 값을 갱신해 줍니다.

window.close() : 현재 실행창이 닫힙니다.

 

option value 접근 예시

	// id로 직접 접근해서 가져오는 방법
	let value = document.getElementById("selid").value;
    
	// name으로 접근해서 가져오는 방법
	value = document.frm.selid.value;
    
	// 네임 안에 option들을 가져온다(배열 = index로 되어 있음)
	// parseInt 시간이 흘러가도록 숫자로 변경하여야 한다.
	value = parseInt(document.frm.selid.options[index].value);

 

 

식별자 (==Access Attribute (접근 속성))

id : 고유한 식별을 목적으로 하는 경우, javascript에서 접근하기, 검사용, html 파일당 한 개만 유효(중복 불가)

class : 재사용을 목적으로 하는 경우, CSS에서 디자인적인 요소, 다중 설정이 가능(중복 허용) 

name :  form 컨트롤 요소의 값(value)을 서버로 전송하기 위해 필요한 속성, 다중 설정 가능(중복 허용)

 

※ 동일한 id명은 불가하지만, id=name명이 같은 경우는 허용된다.


id 사용예제 1

<p id="pid">p tag id pid</p>
<p id="pid">p tag id pid</p>

<script type="text/javascript">
	document.getElementById("pid").innerHTML = 'p태그 입니다';
</script>

 

실행화면

 

 

p tag id pid

p tag id pid

 

설명

동일한 id로 두 개의 태그에 사용할 경우 처음 설정된 p태그만 변경된 것을 볼 수 있다.

id는 고유하기 때문에 한 페이지당 1개만 사용 가능! 중복이 불가하다.

 


id 사용예제 2

<div id="demo" style="background-color: #ffffff">Hello JS CSS</div>
<button type="button" onclick="func()">적용</button>
<script type="text/javascript">
function func() {
	// div태그의 통째를 가져온다(인스턴스)
	let obj = document.getElementById("demo");
	// div태그에 모든 요소에 접근 할 수 있다.
	obj.style.color = "white";
	obj.style.backgroundColor = "blue";
	obj.style.textAlign = 'center';
	obj.style.borderStyle = 'double';
	obj.style.borderColor = "red";
	obj.style.fontFamily = "MS PGothic";
	obj.style.fontStyle = 'italic';
	obj.style.fontSize = '24pt';
}
</script>

실행화면

 

Insert title here
Hello JS CSS

 

설명

div태그에 id값 설정 후 JS 함수 안에서 div태그의 id를 불러오면 div태그의 모든 요소에 접근이 가능하다.

 

 

class 사용예제

<p class="cls"> p tag class cls</p>
<p class="cls"> p tag class cls</p>
<h2 class="cls"> h2 tag class cls</h2>
<script type="text/javascript">
	document.getElementsByClassName('cls')[0].innerHTML = 'class는 cls입니다';
	document.getElementsByClassName('cls')[1].innerHTML = 'class는 cls입니다';
</script>

 

실행화면

 

 

p tag class cls

p tag class cls

h2 tag class cls

 

설명

class는 index 번호로 접근을 할 수 있다. 모든 index에 접근하고 싶다면 for문을 사용하면 된다. 중복 사용 가능!

 

 

name 사용 예제

<p name="name">p tag name name</p>
<h2 name="name">p tag name name</h2>
<script type="text/javascript">
document.getElementsByName('name')[1].innerHTML = "name 입니다";	
</script>

실행화면

 

 

p tag name name

p tag name name

 

설명

name는 index 번호로 접근을 할 수 있다. 모든 index에 접근하고 싶다면 for문을 사용하면 된다. 중복 사용 가능!

 

+ Recent posts