1) 1개 선택
document.querySelector(선택자); => 선택자: '태그', '#아이디명', '.클래스명','[속성=값]'
document.getElementById('아이디');
2) 여러 개 선택
document.querySelectorAll(선택자);
document.getElementByName(이름);
document.getElementByClassName(클래스);
textContent : 값을 추출, html 태그를 문자로 처리(입력된 문자열을 그대로 넣는다.)
innerHTML : 값을 추출, html 태그를 그대로 적용함(입력된 문자열을 HTML 형식으로 넣는다. 단, 보안에 취약함)
값을 추출(읽어오기)
값을 변경(글자를 조작)
addEventListener(이벤트명, 이벤트리스너)
- "DOMContentLoaded" : DOM(Document Object Model 문서객체모델)
문서를 다 읽고 나면 콜백함수를 실행시켜라- ( )=> //화살 함수 function()과 같음
removeEventListener(이벤트명, 이벤트리스너)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.addEventListener("DOMContentLoaded",()=>{
let counter = 0; //클릭수 담을 변수
const h1 = document.querySelector("#clickText");
h1.addEventListener("contextmenu",function(e){
e.preventDefault(); //마우스 오른쪽 버튼이 실행되지 않도록 설정
});
// h1을 클릭할 때마다 숫자가 증가 되어야 함
// h1.addEventListener(이벤트명, 콜백함수); //콜백함수=이벤트리스너=이벤트 핸들러, 이벤트가 발생할 때 실행할 함수
//콜백함수 : 다른 함수의 매개변수로 들어가는 함수
h1.addEventListener("click", function(event){
counter++; //counter = counter +1;
h1.textContent = `클릭 횟수 : ${counter}`;
});
});
/*
1. 문서객체 가져오기
1) 1개 선택
document.querySelector(선택자); => 선택자: '태그', '#아이디명', '.클래스명', '[속성=값]'
document.getElementById('아이디');
2) 여러 개 선택
document.querySelectorAll(선택자);
document.getElementByName(이름);
document.getElementByClassName(클래스);
2. 글자 조작
textContent : 값을 추출, html 태그를 문자로 처리(입력된 문자열을 그대로 넣는다.)
innerHTML : 값을 추출, html 태그를 그대로 적용함(입력된 문자열을 HTML 형식으로 넣는다. 보안에 취약..)
값을 추출(읽어오기) : 문서객체.textContent
문서객체.innerHTML
값을 변경(글자를 조작) : 문서객체.textContent = "원하는 문자열"
문서객체.innerHTML = "원하는 문자열"
3. 이벤트 생성
addEventListener(이벤트명, 이벤트리스너)
4. 이벤트 제거
removeEventListener(이벤트명, 이벤트리스너)
5. 기본적인 이벤트를 제거(막기) : 문서객체.preventDefault()
6. 마우스 오른쪽 버튼 이벤트명 : contextmenu
*/
</script>
</head>
<body>
<h1 id="clickText">클릭 횟수 : 0</h1>
</body>
</html>