쌍용교육센터 - 37일

개발자가 되고 싶어요 ㅣ 2024. 4. 9. 20:37

2024.04.09

클래스를 이용한 문서 객체 탐색

<script>
	window.onload = function(){
		//태그의 class 속성이 지정한 class명과 일치하는 문서 객체를 배열로 반환
		const foo = document.getElementsByClassName('matched');
		let output = '[class명이 matched인 모든 태그의 text 출력]\\n';
		for(let i=0; i<foo.length; i++){
			output += foo[i].innerHTML + '\\n';
		}
		alert(output);
		
		
		//id가 foo인 p xorm qksghks
		const foo2 = document.getElementById('foo');
		//id가 foo인 p 태그의 하위 태그 중 class명이 matched인 태그들을 반환
		const fooMatched = foo2.getElementsByClassName('matched');
		
		let output2 = '[id가 foo인 태그의 하위 태그 중 class명이 matched인 모든 태그의 text명을 출력]\\n';
		
		for(let i=0; i<fooMatched.length;i++){
			output2 += fooMatched[i].innerHTML + '\\n';
		}
		
		alert(output2);
		
		//태그 중에서 class명이 matched와 unmatched 모두 적용된 태그를 반환
		//클래스명이 여러개인 경우 공백을 구분자로해서 문자열로 전달
		//순서는 변경 가능
		const fooMatched2 = foo2.getElementsByClassName('matched unmatched')
		
		let output3 = '[id가 foo인 태그의 하위 태그 중 class명이 matched unmatched인 모든 태그의 text 출력]\\n';
		for(let i=0; i<fooMatched2.length; i++){
			output3 += fooMatched2[i].innerHTML + '\\n';
		}
		
		alert(output3);
	};
</script>

 

QuerySelector

<script>
	window.onload = function(){
		//명시한 선택자를 통해 해당 선택자를 사용하는 태그를 반환
												//css 선택자
		let header1 = document.querySelector('#header_1');
		let header2 = document.querySelector('#header_2');
		
		header1.innerHTML = '서울';
		header2.innerHTML = '부산';
		
		let input1 = document.querySelector('#my_form #input_1');
		input1.value = '홍길동';
		
		
		//CSS 선택자를 명시하면 여러개의 태그를 반환하는 상황에서도
		//querySelector는 같은 태그의 최상단의 태그만 접근 가능 (중요!!)
		let element = document.querySelector('li');
		element.style.backgroundColor='Yellow';
	}
</script>

 

QuerySelectorAll

<script>
		//ul요소의 자식 요소인 li 요소를 모두 탐색하여 반환
											// 자식선택자
		const elems = document.querySelectorAll('ul > li');
		
		for(let i=0; i<elems.length; i++){
			document.write(elems[i].innerHTML + '<br>');
		}
		document.write('-------------------<br>');
		
		// forEach를 사용하면 elems의 결과값이 배열로 인자의 function 인자로 들어간다?
		elems.forEach(function(element){
			element.style.color = 'blue';
		});
		
		
	</script>

 

태그 생성

<script>
	/* 
	메서드 이름						설명
	createElement(tagName)		요소 노드를 생성
	createTextNode(text)		텍스트 노드를 생성
	appendChild(node)			객체에 노드를 연결
	*/
	
	window.onload = function(){
		const header = document.createElement('h1');//h1 태그 생성
		const textNode = document.createTextNode('Hello DOM');//텍스트 생성
		
		//노드 연결
		header.appendChild(textNode);//h1태그에 텍스트를 추가
		document.body.appendChild(header);//body에 h1를 추가
	}
</script>

 

문서 객체의 속성 지정

<script>
	window.onload = function(){
		const img = document.createElement('img');//img 태그 생성
		img.src = '../files/landscape.jpg';
		img.width = 500;
		img.height = 350;
		
		//노드 연결
		document.body.appendChild(img);//img태그가 동적으로 생성
	}
</script>

 

문서 객체의 innerHTML 속성 사용

<script>
	window.onload = function(){
		let output='';
		output += '<ul>';
		output += '<li>JavaSfcript</li>';
		output += '<li>jQuery</li>';
		output += '<li>Ajax</li>';
		output += '</ul>';
		
		//innerHTML 속성에 문자열을 할당
		//document.body.innerHTML = output;//HTML태그 실행
		document.body.textContent = output;//텍스트로만 처리
	}
</script>

 

문서 객체 제거

<script>
	window.onload = function(){
		const willRemove = document.getElementById('will_remove');
		
		//3초 후에 매개변수로 전달된 함수를 호출
		setTimeout(function(){
			//id가 will_remove인 태그 삭제
			//document.body.removeChild(willRemove);
			
			//문서 객체의 하위요소를 모두 제거
			document.body.innerHTML = '';
		},3000);
	};
</script>

 

문서 객체의 스타일 처리

<script>
	window.onload = function(){
		const header = document.getElementById('header');
		/* 
		css background-color 속성은 자바스크립트에서는 backgorundColor로 명시해야 함.
		자바스크립트는 식별자에 '-'을 사용할 수 없음
		*/
		//문서 객체의 스타일을 바꿈
		header.style.border = '2px solid black';
		header.style.color = 'orange';
		header.style.fontFamily = 'Helvetica';
		header.style.backgroundColor = 'yellow';
	};
</script>

 

인라인 이벤트 처리

<input type="button" value="이동" onclick="location.href='https://www.naver.com'">
<input type="button" value="확인" onclick="alert('클릭'); alert('Click');">

 

인라인 이벤트 처리 - 함수 이용

<script>
	function whenClick(){
		alert('클릭!');
	}
</script>
<body>
	<div id="header" onclick="whenClick();">클릭</div>
</body>

 

스크립트(메뉴 만들기)

<script>
window.onload=function(){
	const menu = document.getElementsByTagName('li');
	for(let i=0; i<menu.length; i++){
		//이벤트 연결
		//커서를 태그에 올려놓을 때 이벤트 발생
		menu[i].onmouseover=function(){
			//this : 이벤트가 발생한 태그
			this.style.backgroundColor='#FF0000';
		};
		//커서가 태그를 벗어날 때 이벤트 발생
		menu[i].onmouseout=function(){
			this.style.backgroundColor='#FF8888';
		}
	}
}
</script>

 

스크립트(사진에 마우스 갖다대면 사진 사이즈 키우기)

<script>
	window.onload = function(){
		const bigImg = document.getElementById('bigImg');
		
		const alink = document.getElementsByTagName('a');
		
		for(let i=0; i<alink.length; i++){
			//이벤트 연결
			alink[i].onmouseover = function(){
				bigImg.style.display='';
				//이벤트가 발생한 a태그의 href 속성값(이미지 경로) 반환
				bigImg.src = this.href;
				bigImg.widht = 500;
				bigImg.height = 350;
			};
			alink[i].onmouseout = function(){
				bigImg.style.display='none';
			};
			alink[i].onclick = function(){
				return false;
			};
		}
	};
</script>

 

키보드 입력 시 이벤트

<script>
	/* 
	이벤트 이름			설명								발생 순서
	keydown			키보드 눌러질 때 발생						1
	keypress		글자가 입력될 때 발생(한글로 사용할 수 없음)		2
	keyup			키보드가 떼어질 때							3
	*/
	window.onload=function(){
		//이벤트 연결
		document.getElementById('content').onkeyup = function(){//변수에 객체정보를 담지 않고 아이디로 바로 접근(변수, 상수 한번만 사용하면 바로 연결해도됨)
		//입력한 글자 수
		let inputLength = this.value.length;
		//남은 글자 수를 구함
		let remain = 150 - inputLength;
		
		//문서 객체에 반영
		let letter = document.getElementById('letter');
		letter.innerHTML = remain;
		};
	}
	</script>

 

간단한 회원가입 폼

<script>
	window.onload = function(){
		const form = document.getElementById('register_form');
		//이벤트 연결
		form.onsubmit = function(){
			const name = document.getElementById('name');
			if(name.value.trim()==''){
				alert('이름을 입력하세요!');
				name.value = '';//공백이 있을 경우 공백 제거
				name.focus();
				return false; // false를 반환하면 전송이 안됨
			}
			const id = document.getElementById('id');
			if(id.value.trim()==''){
				alert('아이디를 입력하세요!');
				id.value = '';//공백이 있을 경우 공백 제거
				id.focus();
				return false;
			}
			const password = document.getElementById('password');
			if(password.value.trim()==''){
				alert('비밀번호를 입력하세요!');
				password.value = ''; //공백이 있을 경우 공백 제거
				password.focus();
				return false;
			}
			const zipcode = document.getElementById('zipcode');
			if(zipcode.value.trim()=='' || zipcode.value.length!=5){
				alert('우편번호는 5자리를 꼭 입력하세요!');
				zipcode.value='';
				zipcode.focus();
				return false;
			}
		};
	};
</script>
<body>
<form id="register_form" action="a.jsp" method="post">
	<fieldset>
		<legend>회원가입</legend>
		<ul>
			<li>
				<label for="name">이름</label>
				<input type="text" name="name" id="name" size="10" maxlength="10">
			</li>
			<li>
				<label for="id">아이디</label>
				<input type="text" name="id" id="id" size="10" maxlength="10">
			</li>
			<li>
				<label for="password">비밀번호</label>
				<input type="password" name="password" id="password" size="10" maxlength="10">
			</li>
			<li>
				<label for="zipcode">우편번호</label>
				<input type="text" name="zipcode" id="zipcode" size="10" maxlength="5">
			</li>
		</ul>
		<div align="center">
			<input type="submit" value="전송">
		</div>
	</fieldset>
</form>
</body>

 

간단한 갤러리 만들기

<style>
		*{
			margin:0;
			padding:0;
		}
		#galleryWrap{
			width:520px;
			margin: 0 auto;
			text-align: center;
		}
		#galleryWrap img{
			vertical-align:middle;
		}
		img#prev, img#next{
			cursor:pointer;
		}
</style>

<script>
	window.onload = function(){
		let num = 1;
		let gallery = document.getElementById('gallery');
		//이벤트 연결
		document.getElementById('prev').onclick=function(){
			num--;
			if(num<1){
				num=7;
			}
			gallery.src='../files/img'+num+'.jpg';
		};
		document.getElementById('next').onclick=function(){
			num++;
			if(num>7){
				num=1;
			}
			gallery.src='../files/img'+num+'.jpg';
		};
	};
	</script>
	
	<body>
	<div id="galleryWrap">
		<h1>이미지 넘기기</h1>
		<p>
			<img src="../files/left_btn.png" alt="이전 그림 보기" id="prev">
			
			<img src="../files/img1.jpg" alt="갤러리 그림" id="gallery">
			
			<img src="../files/right_btn.png" alt="다음 그림 보기" id="next">
			
		</p>
	</div>
</body>

'IT 국비 교육' 카테고리의 다른 글

쌍용교육센터 - 39일  (0) 2024.04.12
쌍용교육센터 - 38일  (0) 2024.04.11
쌍용교육센터 - 36일  (0) 2024.04.08
쌍용교육센터 - 35일  (0) 2024.04.05
쌍용교육센터 - 34일  (0) 2024.04.04