λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
JAVASCRIPT

μš”μ†Œ 선택

by _토맀토 2022. 8. 7.
728x90

 

μžλ°”μŠ€ν¬λ¦½νŠΈ μš”μ†Œ 선택

μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œ CSS μ„ νƒμžλ₯Ό λ„˜κ²¨μ„œ μ›ν•˜λŠ” HTML μš”μ†Œλ₯Ό 찾을 수 μžˆλ„λ‘ ν•¨μˆ˜λ₯Ό μ œκ³΅ν•˜κ³  μžˆλ‹€.
λŒ€ν‘œμ μœΌλ‘œ querySelector() ν•¨μˆ˜λŠ” μ„ νƒμžμ— λΆ€ν•©ν•˜λŠ” μš”μ†Œ μ€‘μ—μ„œ 첫 번째 μš”μ†Œλ§Œμ„ λ°˜ν™˜ν•˜κ³ , querySelectorAll() ν•¨μˆ˜λŠ” μ„ νƒμžμ— λΆ€ν•©ν•˜λŠ” λͺ¨λ“  μš”μ†Œλ₯Ό λ°˜ν™˜ν•œλ‹€.


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

λ©”μ„œλ“œ 속성 μž…λ ₯ 방법 : document . λ©”μ„œλ“œλͺ… ( ' μš”μ†Œλͺ… ' )

λ©”μ„œλ“œ μ„€λͺ…
getElementById() HTML μš”μ†Œ 쀑 id 속성인 μš”μ†Œλ₯Ό μ„ νƒν•œλ‹€.
ex) document.getElementById('header')
<div id = header></div>
getElementByClassName() HTML μš”μ†Œ 쀑 classλͺ…μœΌλ‘œ μ„ μ–Έν•œ μš”μ†Œλ₯Ό μ„ νƒν•œλ‹€.
ex) document.getElementByClassName('menu')
<div class = menu></div>
getElementByTagName() HTML μš”μ†Œ 쀑 tagλͺ…μœΌλ‘œ μ„ μ–Έν•œ μš”μ†Œλ₯Ό μ„ νƒν•œλ‹€.
ex) document.getElementByTagName('ul')
<ul></ul>
querySelector() μš”μ†Œμ˜ 선택 방법이 css 선택 방법과 κ°™μœΌλ©° μ„ νƒν•œ μš”μ†Œ 쀑 첫번째 μš”μ†Œλ§Œ μ„ νƒν•œλ‹€.
querySelectorAll() 첫번째 μš”μ†Œλ§Œ μ„ νƒν•˜λŠ” querySelector와 달리 λͺ¨λ“  μš”μ†Œλ₯Ό μ„ νƒν•œλ‹€.

μš”μ†Œ 선택 예제

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

<!DOCTYPE html>
    <html lang="ko">
    <head>
    <meta charset="UTF-8">
    <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>
결과 보기
728x90

'JAVASCRIPT' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

[JAVASCRIPT] λ‚΄μž₯ ν•¨μˆ˜  (4) 2022.08.16
[JAVASCRIPT] λ°°μ—΄ λ©”μ„œλ“œ : join(), push(), pop()  (4) 2022.08.11
μ§€μ—­ν•¨μˆ˜μ™€ μ „μ—­ν•¨μˆ˜  (2) 2022.07.29
ν•¨μˆ˜  (4) 2022.07.26
데이터 νƒ€μž…  (3) 2022.07.26

λŒ“κΈ€


Lucky Charms Rainbow
js
html
css