[36일차] 노드 & 폼 & 이벤트
2023. 2. 13. 16:17ㆍ카테고리 없음
목차
1. 노드 추가/삭제하기
2. 폼 조작하기
3. 이벤트 다루기
1. 노드 추가/삭제하기
1. 노드 추가하기
- 기본 코드
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Node</title>
</head>
<body>
<script></script>
</body>
</html>
- createElement 요소 노드 생성
appendChild 기존 노드에 자식 노드 연결
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Node</title>
</head>
<body>
<script>
const aE1 = document.createElement("a");
document.body.appendChild(aE1);
</script>
</body>
</html>
- createTextNode 텍스트 노드 생성
querySelector() 요소 선택
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Node</title>
</head>
<body>
<script>
const aE1 = document.createElement("a");
document.body.appendChild(aE1);
const txtE1 = document.createTextNode("길벗");
document.querySelector("a").appendChild(txtE1);
</script>
</body>
</html>
- createAttribute 속성 노드 생성
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Node</title>
</head>
<body>
<script>
const aE1 = document.createElement("a");
document.body.appendChild(aE1);
const txtE1 = document.createTextNode("길벗");
document.querySelector("a").appendChild(txtE1);
const hrefAttr = document.createAttribute("href");
hrefAttr.value = 'https://www.gilbut.co.kr';
document.querySelector("a").setAttributeNode(hrefAttr);
</script>
</body>
</html>
2. 노드 삭제하기
- removeChild() 부모 노드에 연결된 자식 노드 삭제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>text 1</p>
<a href="https://www.gilbut.co.kr">길벗</a>
<a href="https://www.sucoding.kr">수코딩</a>
<script>
const childNodes = document.body.childNodes;
childNodes.forEach((node)=>{
if(node.nodeName === "A")
node.parentNode.removeChild(node);
})
</script>
</body>
</html>
2. 폼 조작하기
1. form 태그 선택하기
- form 속성 사용하기
: document 객체의 forms 속성은 모든 form 태그의 노드 정보를 HTMLCollection 객체에 담아 반환
<body>
<form>
<input type="text" name="userid">
</form>
<form>
<input type="text" name="username">
</form>
<form>
<input type="text" name="usernick">
</form>
</body>
- name 속성 사용하기
: form 태그에 name 속성을 사용하면 forms 속성보다 훨씬 직관적으로 form 요소 노드 선택 가능
<body>
<form name ="frm1">
<input type="text">
</form>
<form name ="frm2">
<input type="text">
</form>
<form name ="frm3">
<input type="text">
</form>
</body>
2. 폼 요소 선택하기
- 기본 코드 예시
<body>
<form name="frm1">
<label for="uname">이름</label>
<input type="text" id="uname" name="uname">
<label for="age">나이</label>
<input type="text" id="age" name="age">
<label for="gender">성별</label>
<select id="gender" name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
<button type="submit">전송</button>
</form>
</body>
3. 폼 요소의 입력값 다루기
- 한 줄 입력 요소 다루기
- 한 줄 입력 요소: input 태그의 type 속성값을 text, password, number, url, sesarch, email 등으로 지정했을 때 표시되는 폼 요소
<body>
<form name="frm">
<input type="text" name="id">
<input type="password" name="pw">
</form>
</body>
<body>
<form name="frm">
<input type="text" name="id">
<input type="password" name="pw">
</form>
<script>
document.frm.id.value = 'jscoding';
document.frm.pw.value = 'aaaccc';
</script>
</body>
- 여러 줄 입력 요소 다루기
<body>
<form name="frm">
<textarea name="desc"></textarea>
</form>
</body>
<body>
<form name="frm">
<textarea name="desc"></textarea>
</form>
<script>
document.frm.desc.value = 'setting!';
</script>
</body>
- 체크박스 다루기
<body>
<form>
<label><input type="checkbox" value="apple">사과</label>
<label><input type="checkbox" value="banana">바나나</label>
<label><input type="checkbox" value="orange">오렌지</label>
<label><input type="checkbox" value="melon">멜론</label>
</form>
</body>
<body>
<form>
<label><input type="checkbox" vaule="apple">사과</label>
<label><input type="checkbox" vaule="banana">바나나</label>
<label><input type="checkbox" vaule="orange">오렌지</label>
<label><input type="checkbox" vaule="melon">멜론</label>
</form>
<script>
const checkboxEls = document.querySelectorAll("[type='checkbox']");
for (let i = 0; i < checkboxEls.length; i++) {
checkboxEls[i].checked = true;
}
</script>
</body>
- 라디오버튼 다루기
: 여러 개의 항목 중 하나만 선택하게 할 때 사용하는 폼 요소
<body>
<form>
<label><input type="radio" name="fruits" value="apple">사과</label>
<label><input type="radio" name="fruits" value="banana">바나나</label>
<label><input type="radio" name="fruits" value="orange">오렌지</label>
<label><input type="radio" name="fruits" value="melon">멜론</label>
</form>
</body>
<body>
<form>
<label><input type="radio" name="fruits" value="apple">사과</label>
<label><input type="radio" name="fruits" value="banana">바나나</label>
<label><input type="radio" name="fruits" value="orange">오렌지</label>
<label><input type="radio" name="fruits" value="melon">멜론</label>
</form>
<script>
const radioEls = document.querySelectorAll("[type='radio']");
for(let i = 0; i < radioEls.length; i++){
if(radioEls[i].value === 'banana'){
radioEls[i].checked = true;
}
}
</script>
</body>
- 콤보박스 다루기
: select 태그로 만드는 콤보박스는 여러 항목에서 하나를 선택하는 형태의 폼 요소
<body>
<form>
<select>
<option value="apple">사과</option>
<option value="banana">바나나</option>
<option value="orange">오렌지</option>
<option vaule="melon">멜론</option>
</select>
</form>
</body>
<body>
<form>
<select>
<option value="apple">사과</option>
<option value="banana">바나나</option>
<option value="orange">오렌지</option>
<option vaule="melon">멜론</option>
</select>
</form>
<script>
const optionEls = document.querySelectorAll("option");
for(let i = 0; i < optionEls.length; i++){
if(optionEls[i].value === 'banana'){
optionEls[i].selected = true;
}
}
</script>
</body>
- 파일 업로드 요소 다루기
<body>
<form name="frm">
<input type="file" name="upload">
</form>
</body>
2. 이벤트 다루기
1. 이벤트 등록하기
- 인라인 방식으로 등록하기
<body>
<button onclick="clickEvent()">클릭</button>
<script>
function clickEvent(){
alert("click");
}
</script>
</body>
<body>
<form>
<input type="text" onfocus="focusEvent()" onblur="blurEvent()">
</form>
<script>
function focusEvent(){
console.log("focus on");
}
function blurEvent(){
console.log("focous out");
}
</script>
</body>
- 프로퍼티 리스너 방식으로 이벤트 등록하기
: 요소 노드에 직접 속성응로 이벤트를 등록
<body>
<button>클릭</button>
<script>
const btnE1 = document.querySelector("button");
btnE1.oneclick = function(){
alert("click")
}
</script>
</body>
- 이벤트 등록 메서드로 이벤트 등록하기
: addEventListener() 메서드의 매개변수에 이벤트 타입과 이벤트 함수 전달
<body>
<button>클릭</button>
<script>
const btnE1 = document.querySelector("button");
btnE1.addEventListener("click", function(){
alert("button Click");
});
</script>
</body>
3. 이벤트 객체와 this
1. 이벤트 객체 사용하기
<body>
<button>클릭</button>
<script>
const btnE1 = document.querySelector("button");
btnE1.addEventListener("click", function(event){
console.log(event);
})
</script>
</body>
<body>
<button>클릭</button>
<script>
const btnE1 = document.querySelector("button");
btnE1.addEventListener("click", function(event){
console.log(`clientX:${event.client}`);
console.log(`clientY:${event.clientY}`);
console.log(`pageX:${event.pageX}`);
console.log(`pageY:${event.pageY}`);
console.log(`screenX:${event.screenX}`);
console.log(`screenY:${event.screenY}`);
})
</script>
</body>
- 키보드 이벤트 객체
<body>
<form>
<input type="text">
</form>
<script>
const inputE1 = document.querySelector("input");
inputE1.addEventListener("keydown", function(event){
console.log(`keyCode:${event.keyCode}`);
console.log(`ctrlKey:${event.ctrlKey}`);
console.log(`altKey:${event.altKey}`);
console.log(`shiftKey:${event.shiftKey}`);
})
</script>
</body>
2. 이벤트 취소하기
<body>
<a href="https://www.naver.com">네이버 이동</a>
<a href="https://www.daum.net">다음 이동</a>
<script>
const aEls = document.querySelectorAll("a");
for(let i = 0; i < aEls.length; i++){
aEls[i].addEventListener("click", function(e){
e.preventDefault();
});
}
</script>
</body>