Script는 body태그의 최 하단에 위치하거나,
최하단에 script src = "index.js" 와 같이 JS파일에 연결해주며 시작.
document.getElementById('id');
document - 문서
getElementById('id'); - id라는 이름의 아이디를 가져온다.
document.getElementsByClassName('class');
getElementsByClassName('.class'); - class 라는 이름의 클래스를 가져온다. 깊이와는 상관없이 위에서부터 출력.
존재하지 않는 id 값을 사용하면 null 값이 나타남.
document.getElementsByTagName('태그이름')
document.getElementsByTagName('태그이름'); - 태그이름으로 태그를 선택하여 해당되 모든 태그를 다 가져옴.
document.querySelector('css');
document.querySelector('css'); - css 선택자로 태그 선택하기.
-1. document.querySelector('#ID'); - id를 통해 불러옴. document.getElementById('id');과 같은 효과
-2. document.qurerySelector('.class'); - class명을 통해 불러옴. document.getElementsByClassName('class');와 유사하지만 쿼리셀렉터 이용시 해당 클래스가 들어가있는 요소중 가장 먼저 나온 요소만 나옴.
- 그렇다면, 쿼리셀렉터로 document.getElementsByClassName('class');와 같은 효과를 내려면 어찌하나
= document.querySelectorAll('.class'); 를 사용하면 됨.
Event와 버튼클릭
ex) const btn = document.querySelector('#myBtn');
btn.onclick = function() { // onclick 이라는 프로퍼티에 함수를 할당. 이벤트 핸들러
console.log('hello world!'); // 클릭을 할때마다 특별한 동작 수행.
}
이벤트가 발생했을때 특별한 동작을 하도록 이벤트를 다루는 것 - 이벤트 핸들링
구체적인 동작 - 이벤트 핸들러
alert('message');
- alert 함수를 사용하면 브라우저에 경고창을 띄울 수 있다.
window 객체 - 전역객체.(Global Object)
console.log 또한 window객체로, 앞에 window를 붙여 window.console.log를 해야하지만, 전역객체기 때문에 앞의 window를 빼도 됨.
console.log(window); 하면 다양한 프로퍼티를 보거나 제어할 수 있음.
ex)console.log(window.innerWidht); - 창의 너비
console.log(window.innerHeight); - 창의 높이
console에서 window.open/close 로 창을 켜고 끌 수도 있음.
Window - Web API | MDN (mozilla.org)
Window - Web API | MDN
Window 인터페이스는 DOM 문서를 담은 창을 나타냅니다. document 속성이 창에 불러온 DOM 문서를 가리킵니다. 반대로, 주어진 문서의 창은 document.defaultView를 사용해 접근할 수 있습니다.
developer.mozilla.org
DOM(Document Object Model) - 문서 객체 모델
웹 페이지에 나타나는 html 문서 전체를 객체로
document 객체가 웹 문서의 최상단 객체로, 진입점의 역할.
console.log(document); 를 하면 html 문서가 출력됨.
태그가아니라 객체로 보고싶다면
console.dir(document); 를 해야함.
console.dir 은 문자열 표시 형식
dir은 여러개의 값을 출력할 수 없다.
노드(node)
부모노드 - console.log(myTag.parentElement);
형제노드 - console.log(myTag.previousElementSibling); //왼쪽노드, 우선순위의 노드
console.log(myTag.nextElementSibling);// 오른쪽 노드, 후순위 노드
자식노드 - console.log(myTag.children[x])
console.log(myTag.firstElementChild); // 첫번째 자식 노드
console.log(myTag.lastElementChild); // 마지막 자식노드.
위의 것들은 이어서 사용 가능. ex) console.log(myTag.parentElement.previousElementSibling);
function event1{
console.log('hello');
}
addEventListener('행동(click,submit ....)',event1); 생성
removeEventListener('행동(click,submit ....)',event1); 지우기.
'Js' 카테고리의 다른 글
| getElementsByClassName,querySelector(3/2 공부) (0) | 2023.03.02 |
|---|---|
| forEach문 - check박스를 이용한 비밀번호 표시(비밀번호 보기) (0) | 2023.02.16 |
| 회원가입 유효성 검사 (0) | 2023.02.15 |
| 정규식 (0) | 2023.02.14 |
| 2/14 공부 (1) | 2023.02.14 |