<div class='hello'>
<h1>go on!</h1>
</div>
<button id=bt>버튼</button>
<script>
const title = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
title.innerHTML = "back on";
}
title.addEventListener("click", handleTitleClick);
</script>
queySelctor를 이용해서 class 값 가져오기
addEventListenr이용해서 클릭시 함수 실행 시킬 수 있음
addEventListenr안에서 실행 시킬 수 있는 함수 정의해주기
- innerHTML 이용해서 text 변경
결과
<div class='hello'>
<h1>go on!</h1>
</div>
<button id=bt>버튼</button>
<script>
const title = document.querySelector("div.hello:first-child h1");
const button = document.getElementById("bt")
function clickBt(){
const currentColor = title.style.color;
let newColor;
if (currentColor === 'blue'){
newColor = 'tomato';
}
else {
newColor = 'blue';
}
title.style.color = newColor;
}
button.addEventListener("click", clickBt);
</script>
결과
'웹 개발 > 기초' 카테고리의 다른 글
HTML 클래스 태그 신규 생성 / 제거 (0) | 2021.08.18 |
---|---|
form 텍스트 박스 새로고침 현상 방지 / 브라우저 동작 막기 (0) | 2021.08.18 |
input 입력값 길이 체크하기 (0) | 2021.08.17 |
이벤트리스너 기초2 (0) | 2021.08.17 |
이벤트리스너 기초1 (0) | 2021.08.17 |
이벤트 리스너를 이용해서 스타일 변경