Element 속성 API

요소 태그의 속성을 조회하거나 변경

  • Element.getAttribute(name) : 속성값 가져오기

  • Element.setAttribute(name, value) : 속성값 변경

  • Element.hasAttribute(name) : 속성의 존재 여부를 확인

  • Element.removeAttribute(name) : 속성 삭제

<!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>
</head>
<body>
  <a href="naver.com">naver</a>
  
  <script>
    var a = document.querySelector('a');
    
    // a태그의 href 속성값을 가져옴
    console.log(a.getAttribute('href'));
    
    // a태그의 href 속성값 변경
    a.setAttribute('href', 'daum.net');
    console.log(a.getAttribute('href'));
    
    // a태그에 속성값이 있는지 확인
    console.log(a.hasAttribute('type'))
    
    // a태그의 href속성 제거
    a.removeAttribute('href');
    //속성이 제거되어 false 반환  
    console.log(a.hasAttribute('href')) 
  </script>
</body>
</html>

속성과 프로퍼티

  • 속성을 통한 접근과 프로퍼티를 통한 접근의 값이 다를 수 있음(상대경로의 값이 들어있을때 속성은)

Last updated

Was this helpful?