JavaScript

킹콩·2022년 1월 19일
0

Full Stack Developer

목록 보기
3/9

Document 객체와 HTML element를 가져오는 수많은 함수들을 이용하면 JavaScript에서 HTML 항목을 가져오고 사용할 수 있게 된다.

  • console.log()
    HTML과 유사한 트리에서 요소를 보여준다.
  • console.dir()
    JSON과 같은 트리에서 요소를 보여준다.

Document

브라우저는 HTML 정보가 아주 많이 들어있는 document라는 object를 전달해준다.

HTML document 확장

.location

현재 문서의 URI를 반환한다.


Method

.getElementById()

주어진 ID를 가진 요소의 참조를 반환한다.

const title = document.getElementById("title");
console.dir(title);

.getElementsByName()

.getElementsByClassName()

.getElementsByTagName()

getElements- 는 배열형태로 값을 얻어온다.

.createElement()

const li = document.createElement("li");
const span = document.createElement("span");
span.innerText = "안녕";
li.appendChild(span);

.appendChild(a)

a를 객체의 하위에 종속시킨다

.querySelector()

문서 내에서 주어진 선택자를 만족하는 첫 번째 Element를 반환한다.
".hello:first-child h1"
class hello를 가진 div 내부의 first-child인 h1을 찾아오기

.querySelectorAll()

selector안의 조건에 만족하는 모든 element의 NodeList를 반환한다.


Element

.innerText

가져온 텍스트에 포함된 태그도 하나의 텍스트로 인식하여 보여준다.

const title = document.querySelector(".hello h1");
title.innerText = "hi";

.innerHTML

가져온 텍스트에 포함된 태그를 인식하여 태그를 적용시킨 후 문자를 보여준다.

  • innerText vs innerHTML
    <div style='color:black'>A</div>, A

document.body.appendChild()

body에 html을 추가한다.


EventTarget

.addEventListener()

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
	console.log("title was clicked");
}
title.addEventListener("click", handleTitleClick); 
//클릭 이벤트를 감지하는 방법 1
title.onclick = handleTitleClick;
//클릭 이벤트를 감지하는 방법 2

title이라는 element를 HTML에서 찾아온 후 eventListener를 추가해줘서 click event를 listen하고 click event가 발생하면 handleTitleClick이라는 함수를 동작시킨다.
handleTitleClick()이 아님! JavaScript가 대신에 실행시켜주기를 원하는 것!


Event Handler

사용가능한 event는 element의 console.dir로 확인할 수 있고, property 앞에 on이 붙어다면 event listener이다.
방법 1처럼 사용할 때에는 on을 빼고 "click"과 같이 기재한다.

.onkeydown

keydown 이벤트가 발생했을 때 호출할 코드를 나타낸다

.onkeypress

keypress(en-US) 이벤트가 발생했을 때 호출할 코드를 나타낸다

.onkeyup

keyup(en-US) 이벤트가 발생했을 때 호출할 코드를 나타낸다

.onmouseenter

.onmouseleave


Window

.resize

function handleWindowResize(){
	document.body.style.backgroundColor = "yellow";
}
window.addEventListener("resize", handleWindowResize);

.copy


유용한 Grammar

JSON

  • .stringify()

    object나 array 등 어떤 값이든 string으로 만들어준다.

  • .parse()

    string을

Array

  • .forEach
    array에 있는 각각의 item에 대해 함수를 실행한다.
function sayHello(item){
	console.log(`this is ${item}`);
}
myArray.forEach(sayHello); //방법1
myArray.forEach(item=>{
        console.log(`this is turn of ${item}`);
    }) //방법2. function을 짧게 쓰는 방법!
  • .filter
    지우고 싶은 item을 제외하고 새 array를 만든다.
    item을 지우는 게 아니라 제외하기 때문에 예전 array는 그대로 존재한다.
    filter에서 false를 return하면 그 item은 새 array에 포함되지 않는다.
function sexyFilter(item){return item!== 3}
// 3이 아니면 true를 반환

parseInt()

string을 number로 변환한다.

String()

number을 string으로 변환한다.
String(date.getHours()).padStart(2, "0")

Date()

date.now() 랜덤한 숫자를 제공한다.
date.getHours() 시간을 제공한다.

isNaN()

return type은 boolean으로, Not a Number일 경우 true를 반환한다.

padStart(,)

첫번째 인자는 늘리고자 하는 길이, 두번째 인자는 padding 문자이다.
string만 사용 가능하다.
길이가 1인 문자를 padding "0"을 넣어서 길이를 2로 만들고 싶은 경우
padstart(2, "0")

setInterval(,)

간격을 두고 함수를 실행한다.
첫번째 인자는 실행하고자 하는 함수, 두번째 인자는 간격으로 ms단위이다.

Math()

const chosenImage = images[Math.floor(Math.random() * images.length)];

  • round 반올림 0~10
  • floor 내리기 0~9
  • ? 올리기 1~10

Button

선택한 버튼의 정보를 얻는 방법

function deleteToDo(event){
    console.dir(event.target.parentNode.innerText);
    console.log(event.target.parentElement);
}

버튼을 클릭하는 경우, 첫번째 parameter는 방금 발생한 event에 대한 정보를 담고있다.
event는 target을 주는데, target은 클릭된 HTML element으로 여기서는 버튼이다.
HTML element에는 하나 이상의 property가 있는데 parentElement는 클릭된 element의 부모이다.
즉 버튼의 부모에 접근할 수 있게 된다. 여기서는 버튼의 부모는 li로 li.remove를 하면 항목 제거가 가능하다.

날씨 API

  • Geolocation
    navigator.geolaocation.getCurrentPosition(,)
    브라우저에서 wifi, 위치, GPS 등을 제공한다.
    첫번째 인자에 실행하고자 하는 함수, 두번째 인자는 에러처리 함수
function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;

}  
function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
  • fetch
    JavaScript가 URL을 호출한다.
    fetch(링크)를 하고 개발자도구 Network-All-Preview에서 응답 결과를 확인할 수 있다.
    서버의 응답을 기다리기 위해 then을 사용하고 response를 받아야 한다.
fetch(url).then(response=> response.json()).then(data =>{
        console.log(data);
        console.log(data.name);
    });```
profile
행복하게 살자

0개의 댓글

관련 채용 정보