Web

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ํ•จ์ˆ˜, ๋ฐฑํ‹ฑ, DOM, querySelector

๋…ธ๋ฃจ๋ฃฝ 2021. 1. 15. 03:14

 

ํ•จ์ˆ˜

function sayHello(arg){
  console.log('Hello!', arg);
}

sayHello("HJ");

 

ํ•จ์ˆ˜๋Š” ์ธ์ž(argument)๋ฅผ ๋ฐ›๋Š”๋‹ค.

์ธ์ž๋Š” ์—†์–ด๋„ ๋จ.

 

๋ฐฑํ‹ฑ(``)

function sayHello(name, age){
  return `Hello ${name} you are ${age} years old.`;
}

const greetHJ = sayHello("HJ", 20);

console.log(greetHJ);

""์™€ ''๋Š” ๋‘˜ ๋‹ค String์ด๋‹ค.

ํ•˜์ง€๋งŒ ๋ฐฑํ‹ฑ(``)์€ ์™„์ „ํžˆ ๋‹ค๋ฅธ ๊ธฐ๋Šฅ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.

 

๊ฐ์ฒด ์•ˆ์˜ ํ•จ์ˆ˜

const calculator = {
  plus: function(a, b){
    return a + b;
  },
  
  sub: function(a, b){
    return a - b;
  },

  mul: function(a, b){
    return a * b;
  },

  div: function(a, b){
    return a / b;
  },

  square: function(a, b){
    return a ** b;
  }
}

const plus = calculator.plus(5, 5)
console.log(plus)

const sub = calculator.sub(5, 5)
console.log(sub)

const mul = calculator.mul(5, 5)
console.log(mul)

const div = calculator.div(5, 5)
console.log(div)

const square = calculator.square(5, 5)
console.log(square)

์ฝค๋งˆ ์ฃผ์˜!!

 

DOM (Document Object Module)

<!DOCTYPE html>
<html>
  <head>
    <title>Practice</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1 id="title">This Works!</h1>
    <script src="script.js"></script>
  </body>
</html>
const title = document.getElementById("title");

title.innerHTML = "Hi! From JS";

This Works!๊ฐ€ ์•„๋‹Œ Hi! From JS๊ฐ€ ์ถœ๋ ฅ.

html(์š”์†Œ)์—์„œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์„ ํƒํ•œ ๋ชจ๋“  ๊ฒƒ์€ ๊ฐ์ฒด๊ฐ€ ๋œ๋‹ค. → DOM

๊ฐ์ฒด๋Š” ๋งŽ์€ ํ‚ค๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค. (console๊ฐ์ฒด์˜ .log, .error ๋“ฑ~~)

 

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

title.innerHTML = "Hi! From JS";

console.dir(title);

console.dir์„ ํ•˜๋ฉด ๊ฐ์ฒด๊ฐ€ ์–ด๋–ป๊ฒŒ ๊ตฌ์„ฑ๋๋Š”์ง€ ์ญ‰ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

๊ฐ์ฒด๋ฅผ ํŒŒ์•…ํ•˜๋ฉด title.style.color = 'red'; ๊ฐ™์ด ์ž์œ ๋กญ๊ฒŒ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋‹ค!

 

querySelector

querySelector๋Š” id๋‚˜ ํด๋ž˜์Šค๋ฅผ ๋งŒ์กฑํ•˜๋Š” ๋…ธ๋“œ์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

document.querySelector("#title"); → id๊ฐ€ title์ธ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜.

document.querySelector(".title"); → class๊ฐ€ title์ธ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜.

 

getElementById์™€ ๊ฐ™์€ ๋ช…๋ น์–ด๋Š” ์˜ค์ง id๊ฐ’์œผ๋กœ๋งŒ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ ,

getElementByClassName์€ ํ•ด๋‹น class name์„ ์‚ฌ์šฉํ•˜๋Š” ์—ฌ๋Ÿฌ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํŽธํ•˜๋‹ค.

๋”ฐ๋ผ์„œ, ์•ž์œผ๋กœ๋Š” querySelector()๋ฅผ ์ฃผ๋กœ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค.

 

Event ํ˜ธ์ถœ ์‹œ

function init(){
    title.addEventListener("click", handleClick);
}

handleClick ํ•„์š”ํ•  ๋•Œ ํ˜ธ์ถœ

handleClick() ์ง€๊ธˆ ๋ฐ”๋กœ ํ˜ธ์ถœ