λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
μžλ°”μŠ€ν¬λ¦½νŠΈ

μš”μ†Œ μ„ νƒμž

by Youcodein 2022. 8. 7.
728x90
λ°˜μ‘ν˜•

μš”μ†Œλ₯Ό 직접 μ„ νƒν•˜λŠ” λ©”μ„œλ“œ

μ „μ—­ λ³€μˆ˜μ™€ 지역 λ³€μˆ˜μ˜ μ„ μ–Έ μœ„μΉ˜

λ©”μ„œλ“œ μ„€λͺ…
getElementById() 아이디 μš”μ†Œ μ„ νƒμž. document.getElementById('content')일 경우 HTMLμš”μ†Œ 쀑 id 속성이 'content'인 μš”μ†Œλ₯Ό μ„ νƒν•©λ‹ˆλ‹€.
getElementsByClassName() 클래슀 μš”μ†Œ μ„ νƒμž. document.getElementsByClassName('menu')일 경우 HTMLμš”μ†Œ 쀑 classλͺ…이 'menu'인 μš”μ†Œλ“€μ„ μ„ νƒν•©λ‹ˆλ‹€.
getElementsByTagName() νƒœκ·Έ μš”μ†Œ μ„ νƒμž. document.getElementsByTagName('ul')일 경우 HTMLμš”μ†Œ 쀑 νƒœκ·Έλͺ…이 'ul'인 μš”μ†Œλ“€μ„ μ„ νƒν•©λ‹ˆλ‹€.
getElementsByName() document.getElementsByName('txt')일 경우 HTMLμš”μ†Œ 쀑 nameλͺ…이 'txt'인 μš”μ†Œλ“€μ„ μ„ νƒν•©λ‹ˆλ‹€.
querySelector() μš”μ†Œ μ„ νƒμž. μš”μ†Œμ˜ 선택 방법이 css 선택 방법과 κ°™μŠ΅λ‹ˆλ‹€. μ„ νƒλœ μš”μ†Œ 쀑 첫 번째 μš”μ†Œλ§Œ μ„ νƒν•©λ‹ˆλ‹€.
document.querySelector('.lnb') document.querySelector(div) document.querySelector('#gnb li')
querySelectorAll() λͺ¨λ“  μš”μ†Œ μ„ νƒμž. querySelector()λŠ” μ„ νƒλœ μš”μ†Œ 쀑 첫 번째 μš”μ†Œλ§Œ μ„ νƒν•˜λŠ” 반면 querySelectorAll()은 λͺ¨λ“  μš”μ†Œλ₯Ό μ„ νƒν•©λ‹ˆλ‹€.

예제 3-48

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>μš”μ†Œλ₯Ό 직접 μ„ νƒν•˜λŠ” λ©”μ„œλ“œ</title>
    <script>>
        window.onload = function() {
            var list1 = document.querySelector('#box1 > ul > li');
            var list2 = document.querySelectorAll('#box2 > ul > li');
            console.log(list1);
            console.log(list2);
            //list1.style.background = '#ff6600';
            //list2[0].style.background = '#ccc';
            //list2.item(1).style.background = '#ddd';
        };
    </script>
</head>
<body>
    <div id="box1">
        <ul>
            <li>λ‚΄μš©1</li>
            <li>λ‚΄μš©2</li>
            <li>λ‚΄μš©3</li>
        </ul>
    </div>
    <div id="box2">
        <ul>
            <li>λ‚΄μš©4</li>
            <li>λ‚΄μš©5</li>
            <li>λ‚΄μš©6</li>
        </ul>
    </div>
</body>
</html>
결과 보기
"β€’ λ‚΄μš©1"
"β€’ λ‚΄μš©2"
"β€’ λ‚΄μš©3"

"β€’ λ‚΄μš©4"
"β€’ λ‚΄μš©5"
"β€’ λ‚΄μš©6"
728x90
λ°˜μ‘ν˜•

'μžλ°”μŠ€ν¬λ¦½νŠΈ' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

λ‚΄μž₯ν•¨μˆ˜  (3) 2022.08.15
λ°°μ—΄ κ΄€λ ¨ λ©”μ„œλ“œ  (10) 2022.08.11
μ „μ—­λ³€μˆ˜μ™€ μ§€μ—­λ³€μˆ˜  (5) 2022.08.03
ν•¨μˆ˜ μ΄ν•΄ν•˜κΈ°  (5) 2022.07.28
데이터 νƒ€μž…  (4) 2022.07.26

λŒ“κΈ€