HTML 내부에 자바스크립트 작성
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글자색 바꾸기</title>
<style>
body { text-align:center; }
#heading { color:blue; }
#text {
color:gray;
font-size:15px;
}
</style>
</head>
<body>
<h1 id="heading">자바스크립트</h1>
<p id="text">위 텍스트를 클릭해 보세요</p>
<script>
var heading = document.querySelector('#heading');
heading.onclick = function() {
heading.style.color = "red";
}
</script>
</body>
</html>
외부 스크립트 사용하기(.JS파일)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글자색 바꾸기</title>
<style>
body { text-align:center; }
#heading { color:blue; }
#text {
color:gray;
font-size:15px;
}
</style>
</head>
<body>
<h1 id="heading">자바스크립트</h1>
<p id="text">위 텍스트를 클릭해 보세요</p>
<script src="js/change-color.js"></script>
</body>
</html>
var heading = document.querySelector('#heading');
heading.onclick = function() {
heading.style.color = "red";
}