JavaScript는 HTML에서 불러와지며, JS에서 HTML을 읽고 접근하여 태그를 변경, 생성, 삭제가 가능하다.
이런 행위를 하기위해선 HTML에 태그를 스크립트로 가져와야 한다.
1. HTML ID태그 가져오기
HTML태그를 가져올때 사용하는 키워드는 다음과 같다.
<javascript />const title = document.getElementById("title"); //ID 값으로 태그를 가져옴 const title2 = document.getElementsByClassName("titleStyle"); // 클래스 이름으로 태그를 가져옴 //element를 css방식으로 요소를 가져올 수 있음. querySelector는 맨 첫번째 값만 반환함. const title = document.querySelector(".hello h1"); //맨 첫번째 값만 가져옴 //querySelectorAll은 모든 h1태그 값을 가져옴 const title = document.querySelectorAll(".hello h1"); // querySelector에서 특정id로 요소 찾고싶으면 #을 붙이면 된다. const title = document.querySelector("#hello form"); //id="hello" 인 form을 찾음 // div의 hello 클래스 값을 가진 요소 중 첫번째 h1태그를 가져옴 const title = document.querySelector("div.hello:first-child h1"); //마지막 h1태그 가져옴 const title = document.querySelector("div.hello:last-child h1");
2. HTML 요소 수정하기
가져온 태그의 값을 변경하고 싶을 땐 .innerText=""; 를 사용한다.
<javascript />const title = document.querySelector("h1"); //변수명.innerText = "";로 해당 값을 변경할 수 있다. HTML에서 보는 값이 달라짐 title.innerText = "Hello";
3. JS Event
이벤트는 웹페이지에서 뭔가 행동이 일어났을 때(클릭, 전송, 마우스 움직임 등) 를 의미한다. 예를들어 버튼을 클릭하면 이미지가 변하는 등의 동작을 지시할 수 있다.
3.1. Event listen
이벤트가 발생하는걸 감지하는 방법으로 변수.addEventListener(이벤트 종류, 실행할 동작); 으로 사용한다. 어떤 행동이발생했을 때 그걸 addEventListener하고, 실행할 동작으로 웹 브라우저에 변화를 준다. HTML에서 특정 태그를 가져와서, 해당 태그에 변화가 생기면 동작하도록 JS를 프로그래밍 한다.
이벤트는 현재 브라우저 창 관련 이벤트를 window Event, 현재 웹 페이지 이벤트를 document Event로 지정한다.
<javascript />const title = document.querySeletor("div.hello:first-child h1"); //이벤트를 listen하는법 function handleTitle(){ console.log("title was clicked"); title.style.color = "blue";//h1의 style을 자바스크립트에서 변경함 } function handWindowResize(){ document.body.style.backgroundColor = "tomato"; } //resize는 크롬의 사이즈가 바뀔때를 의미함 title.addEventListener("click", handleTitle);//현재 로드된 웹페이지 이벤트 window.addEventListener("resize",handleWindowResize); //브라우저 이베늩
3.2. EventHandler
JS에는 수많은 이벤트종류(이벤트 핸들러)가 존재한다.
마우스 이벤트 : click, dbclick, mouseover, mouseout, mousemove 등
키보드 이벤트 : keypress, keydown 등
폼 이벤트 : focus, blur, chang, submit 등
다양한 이벤트가 있으니 이건 필요할때 마다 찾아보는게 좋을 듯 하다.
3.3. EventListener로 CSS 변경하기
태그.style을 이용해 특정 이벤트가 발생하면 JS로 css값을 바꾸도록 할 수도 있다.
<javascript />const h1 = document.querySeletor("div.hello:first-child h1"); function handleTitleClick(){ const currentColor = h1.style.color; let newColor; if(currentColor === "blue"){ newColor = "red"; } else{ newColor = "blue"; } h1.style.color = newColor; } h1.addEventListener("click", handleTitleClick);
3.4. JS로 ClassName 변경하기
CSS와 마찬가지로 JS를 이용해 태그의 ClassName을 변경할 수 있다.
<css />h1{ color: blue; } .active { color: red; }
<css />const h1 = document.querySeletor("div.hello:first-child h1"); function handleTitleClick() { const clickedClass = "active"; if( h1.className === clickedClass){ h1.className = ""; }else{ h1.className= clickedClass; } } //h1을 클릭하면 위의 h1.className이 active로 바뀜 h1.addEventListener("click", handleTitleClick); //CSS의 active 클래스의 속성에따라 color가 red로 변경됨
주의할점으로 JS에서 ClassName을 변경하면 기존에 적용되어 있던 값이 사라진다.
이 문제를 해결하는 방법은 두가지 이다.
3.5. ClassName 변경 후 유지하는 방법
3.5.1. ClassList를 선언하여 사용
classList.contains()를 사용하여 기존 classname을 유지할 수 있다. classList.contains()는 ()안에 들어간 클래스가 있는지 확인하고 true,false 값을 반환한다.
<javascript />const h1 = document.querySeletor("div.hello:first-child h1"); function handleTitleClick() { const clickedClass = "active"; if( h1.classList.contains(clickedClass)){ //clieckedClass가 있으면 true h1.classList.remove(clickedClass); }else{//없으면 else구문 실행 h1.classList.add(clickedClass) } } h1.addEventListener("click", handleTitleClick);
3.5.2. toggle 함수 사용
ClassName이 있으면 삭제, 없으면 추가하는 방식으로 동작한다.
<javascript />const h1 = document.querySeletor("div.hello:first-child h1"); function handleTitleClick() { h1.classList.toggle("clicked"); } h1.addEventListener("click", handleTitleClick);
'Develop > Frontend' 카테고리의 다른 글
[JS] 랜덤숫자(난수) 생성 & 이미지 랜덤 생성 (0) | 2024.07.03 |
---|---|
[JS] 반복함수 : setInterval 과 setTimeout (시계구현) (0) | 2024.07.02 |
[JS] 사용자 입력 값(input 등) 가져오기 & 새로고침 이벤트 막기 (0) | 2024.07.02 |
[JS] JavaScript 기초 (0) | 2024.07.02 |
[JS] 자바스크립트 시작하기 - Visual Studio Code (0) | 2024.07.02 |