Javascript/HTML과 JavaScript 연동하기

HTML과 Javascript 연동 (ID의 역할 및 querySelector는?)

appmaster 2021. 2. 2. 17:25

HTML은 UI 역할을 하고, 사용자의 interaction에 따라 동적으로 UI를 업데이트 하고 싶으면 Javascript를 사용해줘야합니다. 보통 interaction이 많을 경우에는 vanila javascript를 이용합니다.

만약 라이브러리를 사용하지않는다면 매우 어려운작업이 되기때문에, react, angular, vue를 사용하는 겁니다.

그래도 연동되는 작동원리를 알아야지 프레임워크를 이용할때 쉽게 이해할 수 있습니다.

 

 

1. HTML에서 ID를 설정하고 Javscript에서 ID를 통해서 DOM과 연결해줍니다.

우선 ID를 설정해야지 자바스크립트에서 쉽게 재어할 수 있습니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <title>Number counts</title>
</head>

<body>
    <h2 id = "number">0</h2>
    <div>
        <button id = "increase">+1</button>
        <button id = "decrease">-1</button>
    </div>


    <script type="text/javascript" src="./practice.js"></script>
</body>
</html>
const number = document.getElementById('number');
const increase = document.getElementById('increase');
const decrease = document.getElementById('decrease');

increase.onclick = ()=>{
    console.log('increase 가 클릭됨.');
}

decrease.onclick = ()=>{
    console.log('decrease 가 클릭됨.');
}

우선 const 변수로 html에 있는 ID값을 다 받아오고 이벤트 설정 해줍니다.

 

 

 

2. 문자형을 정수형으로 변환하기

const number = document.getElementById('number');
const increase = document.getElementById('increase');
const decrease = document.getElementById('decrease');

increase.onclick = ()=>{
    const current = parseInt(number.innerText, 10);
    number.innerText = current +1;
}

decrease.onclick = ()=>{
    const current = parseInt(number.innerText, 10);
    number.innerText = current -1;
}

다음은 ParseInt로 선언하고 number안에 있는 text를 들고와서 문자형을 정수형으로 바꿔주고, 숫자 10은 십진수로 반환하겠다는 의미입니다.

 

 

 

3. 아이디가 없을 경우 querySelector를 이용

const number = document.getElementById('number');
const buttons = document.querySelectorAll('button');
const [increase, decrease] = buttons;


increase.onclick = ()=>{
    const current = parseInt(number.innerText, 10);
    number.innerText = current +1;
}

decrease.onclick = ()=>{
    const current = parseInt(number.innerText, 10);
    number.innerText = current -1;
}

button를 buttons로 다 받아와서 increase와 decrease로 나누어 줍니다.

나누어준 increase값과 decrease값으로 이벤트 처리해줍니다.