Javascript

Javascript DOM 어트리뷰트 조작(getAttribute, setAttribute)

breeghty 2023. 2. 2. 20:21

HTML 문서의 구성 요소인 HTML 요소는 여러 개의  어트리뷰트(속성)을 가질 수 있다.

어트리뷰트는 글로벌 어트리뷰트(id, class, style, title, lang 등)와 이벤트 핸들러 어트리뷰트(onclick, onchange, onfocus, onblur, oninput, on keypress, onkeydown 등)는 모든 html 요소에서 사용할 수 있지만 특정 html 요소에만 한정적으로 사용 가능한 어트리뷰트도 있다. 

 

 1. getAttribute: 속성 값을 가져오는 메서드,  

setAttribute: 속성값을 변경시키는 메서드

 

<body>
    <input type="text" id="user" value="text_1">

    <script>
        const input = document.getElementById('user');

        //value attribute 값 취득
        const inputValue = input.getAttribute('value');
        console.log(inputValue);  //text_1

        //value attribute 값을 변경
        input.setAttribute('value', 'foo');
        console.log(input.getAttribute('value')); //foo

        
    </script>



</body>

2. hasAttribute: 어트리뷰트 속성 값 존재 확인, removeAttribute: 어트리뷰트 속성 값 삭제

<body>
    <input type="text" id="user" value="text_1">

    <script>
        const input = document.getElementById('user');

        //value attribute 값 취득
        const inputValue = input.getAttribute('value');
        console.log(inputValue);  //text_1

        //value attribute 값을 변경
        input.setAttribute('value', 'foo');
        console.log(input.getAttribute('value')); //foo

        if(input.hasAttribute('value')){
            input.removeAttribute('value');
        }

        console.log(input.hasAttribute('value'));//false
    </script>



</body>