[JavaScript] DOM_02

최은서·2023년 11월 8일

5. createElement

createElement(tagName) : 요소 노드를 생성
createTextNode(text) : 텍스트 노드를 생성
appendChild(node) : 객체에 노드를 연결
<title>createElement</title>
<script type="text/javascript">
window.onload=function(){
	//태그 생성
	let header = document.createElement('h1');
	//텍스트 생성
	let textNode = document.createTextNode('Hello DOM');
	//노드 연결
	header.appendChild(textNode); //h1태그에 텍스트 추가
	document.body.appendChild(header); //body에 h1태그 추가
	
};
</script>
</head>
<body>

</body>
</html>
};

6. attribute

<title>문서 객체의 속성 지정</title>
<script type="text/javascript">
window.onload=function(){
	let img = document.createElement('img');
	img.src = '../files/Penguins.jpg';
	img.width = 500;
	img.height = 350;
	
	//노드를 연결
	document.body.appendChild(img);
};
</script>
</head>
<body>

</body>
</html>

7. innerHTML

<title>문서 객체의 innerHTML 속성 사용</title>
<script type="text/javascript">
window.onload=function(){
	let output = '';
	output += '<ul>';
	output += '<li>JavaScript</li>';
	output += '<li>jQuery</li>';
	output += '<li>Bootstrap</li>';
	output += '</ul>';
	
	//innerHTML에 문자열로 작성된 태그를 할당
	document.body.innerHTML = output; //HTML 태그 생성
	
	//document.body.textContent = output; //텍스트로만 처리
};
</script>
</head>
<body>

</body>
</html>

8. removeChild

<title>문서 객체의 제거</title>
<script type="text/javascript">
window.onload=function(){
	let willRemove = document.getElementById('will_remove');
	
	//3초 후에 함수 호출
	setTimeout(function(){
		//문서 객체 제거
		//document.body.removeChild(willRemove);
		
		//문서 객체의 하위 요소를 모두 제거
		document.body.innerHTML = '';
	},3000);
};
</script>
</head>
<body>
	<h1 id="will_remove">Header</h1>
	<h1>Header2</h1>
</body>
</html>

9. style

<title>문서 객체의 스타일 처리</title>
<script type="text/javascript">
window.onload=function(){
	let header = document.getElementById('header');
	/*
	css background-color 속성은 자바스크립트에서는
	backgroundColor로 명시해야 함.
	자바스크립트는 식별자에 '-'를 사용할 수가 없음.
	*/
	header.style.border = '2px solid black';
	header.style.color = 'orange';
	header.style.fontFamily = 'Helvetica';
	header.style.backgroundColor = 'yellow';
};
</script>
</head>
<body>
	<h1 id="header">Header</h1>
</body>
</html>

10. exception

1)

<title>예외처리</title>
</head>
<body>
<script type="text/javascript">
/* 
예외처리를 하지 않은 경우 예외(오류)가 발생하면 프로그램이 중단됨.
예외처리를 했을 경우 예외(오류) 발생시 프로그램 중단 없이 프로그램 실행될 수 있도록 처리
*/
	document.write('예외가 발생하지 않은 경우<br>');
	try{
		document.write('1<br>');
		document.write('2<br>');
	}catch(exception){
		document.write('3<br>');
		console.log(exception); //콘솔에 오류 출력
	}
	document.write('프로그램 종료!!<br>');
	document.write('------------------<br>');
	
	document.write('예외가 발생하는 경우<br>');
	try{
		document.write('1<br>');
		document.write(num); //예외 발생
		document.write('2<br>');
	}catch(exception){
		document.write('3<br>');
		console.log(exception);
	}
	document.write('프로그램 종료!!');
</script>
</body>
</html>

2)

<title>예외처리</title>
</head>
<body>
<script type="text/javascript">
	try{
		let result = 10/0;
		
		if(!isFinite(result)){
			//예외를 일부러 발생시킴
			throw 'DivideByZeroException';
		}
		
		document.write(result);
	}catch(exception){
		document.write(exception);
	}
</script>
</body>
</html>

11. reg

  • 정규표현식(regular expression)은 일정한 패턴을 가진 문자열의 집합을 표현하기 위해 사용하는 형식 언어(formal language)이다.

1)

<title>정규표현식</title>
<script type="text/javascript">
window.onload=function(){
	document.getElementById('register_form').onsubmit=function(){
		let phone = document.getElementById('phone');
		/* 
		/패턴/ --> /(시작) 패턴 /(끝)
		^ 패턴의 시작
		\d 숫자
		{3} 3번 반복
		$ 패턴의 끝
		*/
		//test(문자열) : 정규표현식이 매개변수로 전달된 문자열과 패턴 일치하면 true,
		//				불일치하면 false
		if(!/^\d{3}-\d{4}-\d{4}$/.test(phone.value)){
			alert('000-0000-0000 형식으로 입력하세요');
			phone.value = '';
			phone.focus();
			return false;
		}
	};
};
</script>
</head>
<body>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li>
			<label for="phone">휴대폰</label>
			<input type="text" name="phone" id="phone">
			(000-0000-0000 형식으로 입력)
		</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
</form>
</body>
</html>

2)

<title>정규표현식</title>
<script type="text/javascript">
window.onload=function(){
	//이벤트 연결
	document.getElementById('register_form').onsubmit=function(){
		let phone2 = document.getElementById('phone2');
		/* 
		/패턴/ --> /(시작) 패턴 /(끝)
		^ 패턴의 시작
		[] '[' 와 ']' 사이의 문자들과 match라는 의미
		[] 안의 문자 사이에 하이픈(-)을 사용하게 되면 두 문자 사이의 범위(From - to)와 같은 의미
		[0-9] '['와 ']' 사이의 문자들과 match라는 의미 --> [0123456789]와 같은 의미
		{11} 11번 반복
		$ 패턴의 끝
		*/
		//test보다 느림, 일치하면 검색 데이터를 반환, 불일치 null
		//데이터가 있으면 true, 없으면 false
		if(!phone2.value.match(/^[0-9]{11}$/)){ //0~9까지의 11개의 숫자들만 사용 가능
			alert('11자리 숫자만 입력 가능')
			phone2.value = '';
			phone2.focus();
			return false;
		}
	};
};
</script>
</head>
<body>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li>
			<label for="phone2">휴대폰</label>
			<input type="text" name="phone2" id="phone2">(-없이 입력)
		</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
</form>
</body>
</html>

3)

<title>정규표현식</title>
<script type="text/javascript">
window.onload=function(){
	//이벤트 연결
	document.getElementById('register_form').onsubmit=function(){
		let id = document.getElementById('id');
		/* 
		/패턴/ --> /(시작) 패턴 /(끝)
		^ 패턴의 시작
		[] '['와 ']' 사이의 문자들과 match라는 의미
		[] 안의 문자 사이에 하이픈(-)을 사용하게 되면 두 문자 사이의 범위(From - to)를 의미
		[A-Za-z0-9] '['와 ']' 사이의 문자들과 match라는 의미 --> A~Z, a~z, 0~9까지 사용 가능
		{4,12} 반복 횟수가 4부터 12까지
		*/
		if(!/^[A-Za-z0-9]{4,12}$/.test(id.value)){
			alert('영문 또는 숫자 사용, 최소 4자 ~ 최대 12자를 사용하세요');
			id.value = '';
			id.focus();
			return false;
		}
	};
};
</script>
</head>
<body>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li>
			<label for="id">아이디</label>
			<input type="text" name="id" id="id">
			(영문 또는 숫자 사용, 최소 4자 ~ 최대 12자)
		</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
</form>
</body>
</html>

0개의 댓글