// 해당하는 Id를 가진 요소에 접근하기
document.getElementById()
// 해당하는 모든 요소에 접근하기
document.getElementsByTagName();
// 해당하는 클래스를 가진 모든 요소에 접근하기
document.getElementsByClassName();
**// css 선택자로 단일 요소에 접근하기
document.querySelector("selector");
// css 선택자로 여러 요소에 접근하기
document.querySelectorAll("selector");**
target.addEventListener( type, listener )
https://developer.mozilla.org/ko/docs/Web/Events
const myBtn = document.querySelector("button");
myBtn.addEventListener('click', function(){
console.log("hello world");
})
<p></p>
<input type="text">
<button>Write Something!</button>
중요! myP.textContent = myInput.value;
const myBtn = document.querySelector("button");
const myP = document.querySelector("p");
const myInput = document.querySelector("input");
myBtn.addEventListener('**click**', function(){
myP.textContent = myInput.value;
});
// input 요소에 'input' 이벤트를 연결하면 실시간으로 값이 반영되게 만들 수도 있습니다.
myInput.addEventListener('**input**', ()=>{
myP.textContent = myInput.value;
});
026.html )
myP.innerHTML = "<strong>I'm Strong!!</strong>";
myP.outerHTML = "<div></div>";
// innerText 속성은 요소의 **렌더링된** 텍스트 콘텐츠를 나타냅니다.
//(**렌더링된**에 주목하세요. ****innerText는 "사람이 읽을 수 있는" 요소만 처리합니다.)
// textContent 속성은 노드의 텍스트 콘텐츠를 표현합니다
innerHTML
요소(element) 내에 포함된 HTML 마크업을 가져오거나 설정
태그 이름들이 나오지 않고, 우리가 평소 html 작성한 것처럼 텍스트만 깔끔하게 보임
단점: 경고, 보안에 취약하기 때문에 사용 지양
! 주의 사항 !
인라인으로 JS나 style 등을 적어서 오류 만들지 말기
무조건 js, css ,html 파일 따로따로 만들어서 관리하자
ex) onclick도 같이 인라인에 쓸 것을 addEvetListner(’click’, listner)로 사용
//string으로 넣어도 (이미지 로드 실패)오류가 뜨는 경우임
const name = "<img src='x' onerror='alert(1)'>";
document.querySelector('div').innerHTML = name; // shows the alert
innerText 와 textContent
const myP = document.querySelector("p");
myP.innerText = "<strong>I'm Strong!!</strong>";
myP.textContent = "<strong>I'm Strong!!</strong>";
❗ innerText
❗ textContent
요소 노드를 주어진 위치에 배치
<strong class="sayHi">
반갑습니다.
</strong>
const sayHi = document.querySelector('.sayHi');
sayHi.insertAdjacentHTML('beforebegin', '<span>안녕하세요 저는</span>');
sayHi.insertAdjacentHTML('afterbegin', '<span>재현입니다</span>');
sayHi.insertAdjacentHTML('beforeend', '<span>면접오시면</span>');
sayHi.insertAdjacentHTML('afterend', '<span>치킨사드릴게요</span>');
1. DOM 안에서 노드 탐색
노드 ≠ 요소 (노드 범위 안에 요소가 있는 것)
암기하기
<!-- 주석입니다 주석. -->
<article class="cont">
<h1>안녕하세요 저는 이런 사람입니다.</h1>
<p>지금부터 자기소개 올리겠습니다</p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt incidunt voluptates laudantium fugit, omnis
dolore itaque esse exercitationem quam culpa praesentium, quisquam repudiandae aut. Molestias qui quas ea iure
officiis.
<strong>감사합니다!</strong>
</article>
const cont = document.querySelector(".cont");
console.log(cont.firstElementChild); // 첫번째 자식을 찾습니다.
console.log(cont.lastElementChild); // 마지막 자식을 찾습니다.
console.log(cont.nextElementSibling); // 다음 형제요소를 찾습니다.
//previousElementSibling: 이전 형제 요소를 찾는 게 따로 있음 != 노드
console.log(cont.previousSibling); // 이전 형제노드를 찾습니다.
console.log(cont.children); // 모든 직계자식을 찾습니다.
console.log(cont.parentElement); // 부모 요소를 찾습니다.
const btnFirst = document.querySelector('.btn-first');
//이벤트핸들러 = 이벤트리스너라고 부른다
btnFirst.addEventListener('click', (event) => {
console.log(event); //event는 자동완성으로 만들어진 것, 이름은 내 마음대로 바꿔도 됨, e로 많이 씀
});
//원범님의 설명
**function handleClick(param){
return function(event){
}
}
element.addEventListener("click",handleClick(뭐변수이런거))**
면접에서 다수 기출됨으로 냅다 압기하기
이 이벤트 흐름이 이벤트 객체 정보에 싹 들어가있는 거
[이벤트 흐름 설명]
이벤트가 시작된다 (ex- click)
1단계 캡처링
2단계 버블링
addEventListener
실행—> 항상 캠처링 이벤트 핸들러가 먼저 실행됨!! 마크업이 버블링보다 뒤에 있어도 실행은 캡처링이 우선
<article class="parent">
<ol>
<li><button class="btn-first" type="button">버튼1</button></li>
<li><button type="button">버튼2</button></li>
<li><button type="button">버튼3</button></li>
</ol>
</article>
<script>
const parent = document.querySelector('.parent');
parent.addEventListener('click', function (event) {
console.log(event.target); // 이벤트가 발생한 바로 그 요소, 버튼 그 자체
console.log(event.currentTarget); // 이벤트와 연결된 부모요소
})
</script>
<li></li>
이벤트가 발생한 바로 그 요소<article class = “parent”></article>
이벤트와 연결된 부모요소<script>
const parent = document.querySelector('.parent');
parent.addEventListener('click', function (event) {
console.log(event.target); // <li></li>
//event.target.nodeName을 넣으면 노드네임 확인 가능
console.log(event.target.nodeName); LI
if (event.target.nodeName === "BUTTON") {
event.target.innerText = "버튼4";
}
})
</script>
this는 이벤트가 연결된 노드를 참조
일반 함수는 <article class=”parent”>
를 가르킨다. 이벤트가 연결된 요소
화살표 함수로 바꾸면 this는 바로 자신의 부모 scope를 참조함
<div></div>
<article class="parent">
<ol>
<li><button class="btn-first" type="button">버튼1</button></li>
<li><button type="button">버튼2</button></li>
<li><button type="button">버튼3</button></li>
</ol>
</article>
<script>
const parent = document.querySelector('.parent');
parent.addEventListener('click', (event) => {
console.log(this);
})
//일반 함수는 parent를 가르킨다. 이벤트가 연결된 요소
// 화살표 함수로 바꾸면 this는 바로 자신의 부모 scope를 참조함,
</script>