본문 바로가기
Javascript/element

Element.setAttribute(), Element.getAttribute(), Element.removeAttribute()

by NANDEV 2022. 11. 8.

Element.setAttribute()

Element의 속성 값을 지정된 이름과 값으로 설정한다. 속성이 이미 있는 경우 값이 업데이트된다.

Element.setAttribute(name, value);

 

Element.getAttribute()

Element의 지정된 이름의 속성 값을 반환한다. 존재하지 않는 속성 이름을 입력하면 null을 반환한다.

Element.getAttribute(name);

 

Element.removeAttribute()

Element의 지정된 이름의 속성 값을 제거한다.

Element.removeAttribute(name);

 

<!DOCTYPE html>
<html lang="en">
  <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>setAttribute</title>
  </head>
  <body>
        <button type="button" class="btn btn--prev">Prev</button>
        <button type="button" class="btn btn--next">Next</button>
  </body>
  
  <script>
  	const prevBtnEl = document.querySelector('.btn--prev');
	prevBtnEl.setAttribute('type', 'submit');
	prevBtnEl.setAttribute('disabled', '');
    
	console.log(prevBtnEl.getAttribute('type')); // 'submit'
    
	prevBtnEl.removeAttribute('disabled');
	console.log(prevBtnEl.getAttribute('disabled')); // null
  </script>
</html>
반응형

댓글