JavaScript

dom 강의 정리

연93 2022. 8. 17. 15:44

 

<body>

    <h1 class="title" style="color:red;">Hello</h1>
    <h1 class="title" style="color:red;">Hello</h1>
    <img src="#" alt="kitten">

    <script>
        // getAttribute 예제
        // 1. DOM객체를 가지고 온다.
        const h1Elem = document.querySelector('.title');

        // 2. 가지고온 객체의 속성을 알아낸다.
        let styleAttr = h1Elem.getAttribute('style');
        

        // 3. 새로운 속성을 추가한다.
        styleAttr += 'border:1px solid red;'
        console.log(styleAttr);

        // 4. 적용한다.
        h1Elem.setAttribute('style', styleAttr);

        // setAttribute 예제
        // 1. DOM객체를 가지고 온다.
        const imgElem = document.querySelector('img');
        
        // 2. 객체에 속성을 설정한다.
        const imgSrc = 'https://placekitten.com/200/200';
        imgElem.setAttribute('src', imgSrc);       

    </script>
    
</body>
<body>
    <h1 id="main-title"></h1>
    <div id="description">
    </div>

    <script>
        const h1Elem = document.querySelector('#main-title');
        console.log(h1Elem);

        h1Elem.textContent = "Hello World";


        const divElem = document.querySelector('#description');
        console.log(divElem);

        divElem.innerHTML = '<h3>Welcome</h3>';


    </script>
    
</body>
<body>

    <h1>Welcome</h1>


    <script>
        // 1. 새로운 Element를 만든다.
        const h1Elem = document.createElement('h1');

        // 2. Element를 설정한다.
        h1Elem.textContent = 'Hello World';

        // 3. body에 붙여넣어준다.
        document.body.appendChild(h1Elem);


        // Welcome을 삭제한다.
        setTimeout(()=>{
            const target = document.querySelector('h1');
            console.log(target);

            target.parentNode.removeChild(target);

        }, 3000)

        
    </script>
    
    
</body>

'JavaScript' 카테고리의 다른 글

Stack 강의 정리  (0) 2022.08.19
dom 강의2  (0) 2022.08.18
bubblesort 강의 정리  (0) 2022.08.16
콜백 함수 정리  (0) 2022.08.14
스코프 강의 내용 22.08.11  (0) 2022.08.11