자바스크립트와 웹 프론트엔드 공부

박서연·2023년 1월 28일
0

javascript 기초 탄탄

목록 보기
2/2

페이지는 문서의 구조를 나타내는 html, 각 스타일을 나타내는 css, 정적 구조와 스타일에 변화를 주거나 로직을 추가하는 js가 함께 동작.
이때 브라우저는 js코드를 실행시키면서 html, css 변화가 생기면 rendering해 변화가 생기도록 해줌.

1. DOM 소개

js를 통해 html 문서에 접근 가능한 것은, html이 dom인터페이스를 통해 기술되어 객체로서 js와 연결되기 때문!

  • dom : document object model의 약자.
    • 컴퓨터가 문서를 잘 처리할 수 있도록 문서의 구조에 대해 약속한 것.
    • Tree형태로 표현.
    • 각 노드에 하나의 부모가 있고, 자식들이 있음.
<html>
   <head>
  </head>
  <body>
  </body>
<html>

document.children을 하면 모든 항목을 접근 가능하고,
document.children[0].children[0]을 하면 <head></head> 태그에 접근이 가능
document.children[0].children[1]을 하면 <body></body> 태그에 접근이 가능
document.children[0].children[1].parentNode를 하면

<html>
   <head>
  </head>
  <body>
  </body>
<html>

에 다시 접근할 수 있음.
이렇게 부모와 자식간을 오가면서 원하는 object에 오갈 수 있음.
또한, 첫번째 자식, 마지막 자식, 형제들에 접근도 가능.

firstElementChild(), lastElementChild(), nextElementSibling(), previousElementSibling()

head = document.children[0].children[0] 후
head.firstElementChild 또는 link.previousElementSibling을 조회해보면 을 조회할 수 있고,
head.lastElementChild, link.nextElementSibling을 조회해보면 이 나옴.



2. Document API

html의 특정 문서를 dom api를 이용해서 가져오는 방법

  • 단일 element 선택
//getElement가 해당 역할을 함. (getElements는 여러개를 반환)
var t = document.getElementById //element의 id 속성으로 검색 해 해당 id를 반환해 줌.

t.innerHTML
t.innerText //html 코드가 제거된 text를 반환
t.innerText = "<i>hello</i>" // 실제 컨텐츠가 변경됨.
//단, innerText는 text로 들어가고, innerHTML을 변경하면 html 코드가 적용되서 변경됨

t.style.color
t.style.fontSize //등 여러 요소 변경 가능
var t2 = document.getElementById("logo");
//t에는 <p> tag, t2에는 <img> tag라고 해보자.
//이때 t와 t2 둘 다 src를 가지고 있지만, t.src는 접근이 안되고 t2.src는 접근이 됨.
//원래 src가 정의되지 않은 tag에 대해서는 동기화 시켜주지 않음.
//하지만 
getAttribute("src") //를 사용하면 해당 문제를 해결할 수 있음.
getAttribute("src", "어쩌고"); // 오른쪽 내용으로 변경됨!
  • 다중 element 선택하기
    여러 형태를 가져오는 만큼, 배열 형태로 가져오게 됨.
document.getElementsByTagName("p"); // 모든 p 태그들이 배열로 반환됨.
document.getElementsByClassName("lyric"); // lyric classname을 가진 부분들이 반환.
a = document.getElementsByName("author")[0];
a.value // 해당 값을 가져올 수 있음.
a.value="박서연" //해당 값을 바꿀 수도 있음.
a.getAttribute("value"); // null을 반환. input tag에 입력된 값은 element의 속성으로는 동기화 되지 않기 때문!


3. css selector를 이용한 element 선택

//해당 메소드의 원하는 element를 나타내는 selector로써 기술해 넘기면 dom에서 해당 조건을 만족하는 element를 반환해 줌.
document.querySelector // 하나의 element만 반환.
document.querySelectorAll //조건을 만족하는 모든 element 반환.

selector 문법은 css 문법과 동일.

#을 사용한 경우에는 id, tag이름은 그대로, class이름의 경우에는 .classname으로.
이외에도 꺽쇠를 이용해서 자손 검색이나 ,를 이용해서 여러가지를 선택할 수도 있음.

이렇게 선택된 element는 역시나 값을 변경도 가능.



4. element 추가, 삭제

hr = document.createElement("hr"); // hr태그가 생성되어 hr 변수에 저장
document.body.appendChild(hr); // 추가할 element를 인자로 받고, 호출된 element(여기서는 body)의 가장 마지막에 자식으로 인자를 추가함.
document.insertBefore(추가할 element, document.body.children[3]처럼 원하는 위치); // 마지막이 아닌 원하는 위치에 추가하는 방법
hr2 = hr.cloneNode(); // hr element가 복사된 것이 hr2로 들어감!
document.insertBefore(hr2, document.body.children[6]);
document.body.removeChild(hr2); //삭제


5. callback Function

  • callback 함수 : 조건을 등록해두고 그 조건을 만족한 경우, 나중에 호출되는 함수
function callback(){ console.log("callback function is called");}
setTimeout(callback, 3000); // time 시간이 지난 경우 function 함수를 콜백

setInterval(callback, 5000); // time 시간이 경과할 때마다 function 함수를 콜백 (계속 반복) -> clearInterval 함수를 통해 멈출 수 있음.

clearInterval(2); // setInterval 함수의 호출 결과로 반환된 intervalld를 인자로 받아 주기적으로 호출되던 function 호출으 취소


6. HTML Tag 속성에 EventHandler 추가

  • form Event : html 문서의 form element에 변화가 생기거나 submit 버튼을 누를 경우 발생
  • window Event : 페이지가 모두 로드 되었을 때 발생하는 onload event 등이 있음
  • mouse Event : 사용자가 마우스를 조작했으 때 발생
  • key evnet : 사용자가 키보드를 조작했으 때 발생
<h1 onclick="console.log('clicked');"> HTML Tag 속성 event handler 추가 </h1>
<input type="text" onchange="console.log('changed');" onkeydown="console.log('typed'); >
//onkeydown : input 창이 클릭된 경우 출력

event가 발생하고 해당 handler가 호출되는 과정을 트리거된다고 표현.



7. JS에서 EventHandler 설정

//a.html
<html>
  <head>
  	<meta charset = "utf-8">
  </head>

  <body>
      <form
		method = "GET" action "b.html" id="form1">
          
        이름 : <input type="text name="id"><br>
        메세지 : <input type="text" name="msg"><br>
        <input type="submit">
      </form>


  </body>
</html>

submit 버튼을 누르면 get method를 통해 간단한 메세지가 전달.

//a.html
<html>
  <head>
  	<meta charset = "utf-8">
  </head>

  <body>
      <form
		method = "GET" action "b.html" id="form1"
		onsubmit="console.log('from tag'); return false;">
          
        이름 : <input type="text name="id"><br>
        메세지 : <input type="text" name="msg"><br>
        <input type="submit">
      </form>


  </body>
</html>

onsubmit에서 return false를 한 이유는 브라우저에서 기본적으로 b.html으로 해당 정보를 넘기는 파트를 비활성화 시키기 위함!

이 경우에는 from tag는 나오지만, 메세지와 이름이 전송되지는 않음.
이런 false 기능은 다른 기능에서도 사용할 수 있음.

메세지 : <input type="text" name="msg" onkeydown="return false;"><br>

onkeydown에서 return false를 하면, 메세지 부분에서 키보드를 입력해도 타이핑되지 않음!

<script>
	var t = document.getElementById("form1");
	t.onsubmit = function a(){
    	console.log("from property");
      	return false;
    }
</script>

위의 코드에 이 스크립트를 추가하면, 위의 핸들러는 작동하지 않고 밑에 코드가 덮여쓰여짐.

<script>
 function b(){
	console.log("from addEventListener");
  	return false;
}
  t.addEventListener("submit", b);
</script>

이 코드를 통해서도 eventhandler를 추가할 수 있음!
위의 script와 합쳐서 작성해도 이번에는 덮여쓰이지 않고 둘 다 실행됨.

addEventListener()는 덮여쓰이지 않아 여러개를 사용할 수 있다는 것이 특징

profile
좋은 사람들과 좋은 시간을 보내기 위한 프론트엔드 개발자

0개의 댓글