Develop/자바스크립트 (JavaScript)

[JavaScript] Week1

안다희 2019. 1. 21. 19:57
728x90

https://github.com/YOOGOMJA/javascript_study


solution branch에 답 있음


[example1.html]


1. getElementById로 요소 찾기


개발자도구(f12) - console을 보자!

 

입력) document.getElementById("head1")

결과) <h1 id='head1'>Hello World!</h1>



- class와 id의 차이

class는 카테고리화

id는 그 요소 하나를 딱 집어서 할 때!



2. getElementsByClassName으로 요소 찾기

입력) document.getElementsByClassName("head1")[0]
결과) <h1 class='head1'>Hello!</h1>

class는 여러 개의 '의자'를 가져온다고 생각하기 때문에 (이게 표준) elements인거다!



3. 요소 생성하기

입력) document.createElement("h1")

결과) <h1></h1>


근데 console에서 진행해도 똑같다 vscode에서 진행하는거랑 같아


3.1 요소 추가하기

var createdElem = document.createElement("h1");
createdElem.innerText = "Jello!";
elem.append(createdElem);




4. 요소 삭제하기

for(var i = 0 ; i < elem.children.length ; i++){
var item = elem.children[i];
if(item.innerText === "World!"){
item.remove();
}
}

근데 === 주의!





===================================


[example2.html]


.innerText했는데 안나오면 .value~


console.log(document.getElementById("elem")) 

콘솔에 찍는다


디버깅할 때 console.log(함수, int, string, 배열) 등등 아무거나 들어가도 됨

아주 많이 쓰는 것! console.log!!!!






[prac1.html]




- <list>의 자식요소 개수 출력하기

입력) count.innerText = list.children.length;
출력) count에는 list의 자식개수가 출력됨.



trim은 띄어쓰기로만 구성된 공백문자여도 다 공백으로 처리!!

"  ".trim() = ""

"    ".trim() = ""

"".trim() = ""


[prac2.html]


- <Element(tagName) attribute=""> 주의!

- 어디서든 .value 잊지않기 txtMaj2.innerText = txtMaj.value;


- 버튼 추가하기

var btn = document.createElement("input");
btn.type = "button";
btn.innerText = "삭제";
btn.setAttribute("onClick", "remove(this)");
tr.append(btn);





- table 찾고 tbody도 찾기. 그러나 tbody에 id가 없을때! -> getElementsByTagName("tbody")[0] 

- s 니까 [] 필수!!!


var tblList = document.getElementById("tblList");
tblList.getElementsByTagName("tbody")[0].append(tr);



- 삭제하기

function remove(target){
// ## 삭제 버튼을 클릭하면
// 현재 행을 삭제합니다.
var tr = target.parentElement.parentElement.remove();
// 현재 요소의 부모요소는 parentElement로 접근할 수 있습니다.
}

target은 button에서 (this)로 한거다. 그러니까 tr은 button의 부모(td)의 부모(tr)이다!



- 빈칸 검사

if (txtMaj.value.trim() === "" || txtName.value.trim() === "" || txtDeg.value.trim() === "") {
alert("빈칸을 채워주세요");
return;
}