querySelector

์ง€๋‚œ ์‹œ๊ฐ„์— ์ž‘์„ฑํ–ˆ๋˜ ์ฝ”๋“œ์— ์ด์–ด์„œ querySelector ๋ผ๋Š” ์„ ํƒ์ž๋ฅผ ์•Œ์•„๋ณด์ž.

<ul class="list-group" id="list1">
    <li class="list-group-item">An item</li>
    <li class="list-group-item">A second item</li>
    <li class="list-group-item">A third item</li>
    <li class="list-group-item">A fourth item</li>
    <li class="list-group-item">And a fifth one</li>
</ul>

<script>
    document.querySelector('.list-group')
    document.querySelector('#list1')

    document.querySelectorAll('.list-group-item')[4]

</script>

querySelector('.list-group') ๋ผ๊ณ  ํ•˜๋ฉด class๊ฐ€ list-group ์ธ ์š”์†Œ๋ฅผ ์ฐพ์•„์ค€๋‹ค.

querySelector('#list1') ๋ผ๊ณ  ํ•˜๋ฉด id๊ฐ€ list1 ์ธ ์š”์†Œ๋ฅผ ์ฐพ์•„์ค€๋‹ค.

css์—์„  . ์ด ํด๋ž˜์Šค #์ด id ๋ผ๋Š” ๋œป์ด๋‹ค.

ํ•˜์ง€๋งŒ querySelector๋Š” ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋งŒ ์ฐพ์•„์ค€๋‹ค.

document.querySelector('.list-group-item')

์œ„ ์ฝ”๋“œ๋Š” ์ฒซ๋ฒˆ์งธ list-group-item ๋งŒ ์ฐพ์•„์ค€๋‹ค.

<li class="list-group-item">An item</li>

๊ทธ๋ž˜์„œ ๋™์ผํ•œ ํด๋ž˜์Šค ๋ช…์ด ์ค‘๋ณตํ•ด์„œ ์‚ฌ์šฉ๋  ๋•Œ์—๋Š”

 document.querySelectorAll('.ํด๋ž˜์Šค์ด๋ฆ„)'[n]

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํ•ด๋‹น ํด๋ž˜์Šค ์ด๋ฆ„์˜ n๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ฐพ์•„์ค€๋‹ค.

โœจ ๊ณผ์ œ. ์ง€๋‚œ์‹œ๊ฐ„์— ๋งŒ๋“ค์—ˆ๋˜ script๋ฅผ querySelector ์™€ querySelectorAll์„ ์‚ฌ์šฉํ•ด์„œ ๋ฐ”๊ฟ”๋ณด์ž.

<script>
    document.getElementsByClassName('navbar-toggler')[0].addEventListener('click', function() {
        //๋ฒ„ํŠผ ํด๋ฆญ ์‹œ show class ์ถ”๊ฐ€
        document.getElementsByClassName('list-group')[0].classList.add('show');
        //๋ฒ„ํŠผ ํด๋ฆญ ์‹œ show class Toggle
        document.getElementsByClassName('list-group')[0].classList.toggle('show');
    })
</script>

Last updated