JavaScript DOM Tutorial with Example - Lee-hyuna/33-js-concepts-kr GitHub Wiki

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ DOM์ด ๋ญ˜๊นŒ?

JavaScript๋Š” DOM(Document Object Model)์„ ์‚ฌ์šฉํ•˜์—ฌ ์›น ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ์š”์†Œ์— ์•ก์„ธ์Šคํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์‹ค์ œ๋กœ ์›น ๋ธŒ๋ผ์šฐ์ €๋Š” ํŽ˜์ด์ง€๊ฐ€ ๋กœ๋“œ๋˜๋ฉด ์›น ํŽ˜์ด์ง€์˜ DOM์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. DOM ๋ชจ๋ธ์€ ์ด์™€ ๊ฐ™์€ ๊ฐœ์ฒด์˜ ํŠธ๋ฆฌ๋กœ ์ž‘์„ฑ๋ฉ๋‹ˆ๋‹ค.




DOM๊ณผ ์ด๋ฒคํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ• ๊นŒ?

DOM์„ ์‚ฌ์šฉํ•˜์—ฌ JavaScript๋Š” ์—ฌ๋Ÿฌ task๋ฅผ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ƒˆ ์š”์†Œ์™€ ์†์„ฑ์„ ๋งŒ๋“ค๊ณ  ๊ธฐ์กด ์š”์†Œ์™€ ์†์„ฑ์„ ๋ณ€๊ฒฝํ•˜๋ฉฐ ๊ธฐ์กด ์š”์†Œ์™€ ์†์„ฑ์„ ์ œ๊ฑฐํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. JavaScript๋Š” ๊ธฐ์กด ์ด๋ฒคํŠธ์— ๋ฐ˜์‘ํ•˜๊ณ  ํŽ˜์ด์ง€์— ์ƒˆ ์ด๋ฒคํŠธ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

getElementById, innerHTML Example

  1. getElementById ID๋ฅผ ์š”์†Œ์˜ ์†์„ฑ๊ฐ’์œผ๋กœ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
  2. innerHTML ์š”์†Œ์˜ ๋‚ด์šฉ์„ ์•ก์„ธ์Šคํ•ฉ๋‹ˆ๋‹ค.

<html>
<head>
    <title>DOM!!!</title>
</head>
<body>
    <h1 id="one">Welcome</h1>
    <p>This is the welcome message.</p>
    <h2>Technology</h2>
    <p>This is the technology section.</p>
    <script type="text/javascript">
        var text = document.getElementById("one").innerHTML;
        alert("The first heading is " + text);
    </script>
</body>
</html>

getElementsByTagName Example

getElementsByTagName ํƒœ๊ทธ ์ด๋ฆ„์„ ์‚ฌ์šฉํ•˜์—ฌ ์š”์†Œ์˜ ์†์„ฑ์— ์…‹ํŒ…์„ ํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ๋™์ผํ•œ ํƒœ๊ทธ ์ด๋ฆ„์„ ๊ฐ€์ง„ ๋ชจ๋“  ํ•ญ๋ชฉ์˜ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

<html>
<head>
    <title>DOM!!!</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>This is the welcome message.</p>
    <h2>Technology</h2>
    <p id="second">This is the technology section.</p>
    <script type="text/javascript">
        var paragraphs = document.getElementsByTagName("p");
        alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
        document.getElementById("second").innerHTML = "The orginal message is changed.";
    </script>
</body>
</html>

Event handler Example

  1. createElement ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
  2. removeChild ์š”์†Œ๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
  3. ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํŠน์ • ์š”์†Œ์— Event handler๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
document.getElementById(id).onclick = function() {
    lines of code to be executed
}

OR

document.getElementById(id).addEventListener("click", functionname)

<html>
<head>
     <title>DOM!!!</title>
</head>
<body>
    <input type="button" id="btnClick" value="Click Me!!" />
    <script type="text/javascript">
        document.getElementById("btnClick").addEventListener("click", clicked);
        function clicked() {
   	    alert("You clicked me!!!");
        }	
  </script>
</body>
</html>
โš ๏ธ **GitHub.com Fallback** โš ๏ธ