[js + browser] HtmlElement.style 대신 window.getComputedStyle(~) 를!

식빵·2022년 12월 7일
0
post-thumbnail

이번에 프론트 단 개발을 하고 있는데,
현재 화면에 display block 이 되어있는 팝업창이 있다면 한번에 닫도록 하려고 했다.
그래서 아래처럼 코딩했다.

잘못된 코드

Array.from(document.querySelectorAll('.popupDiv')) // 팝업 DIV 를 모두 선택하여 배열로 변형
  .filter(div => div.style.display !== 'none') // style {display: none}인 걸 필터
  .forEach(div => div.style.display = 'none'); // 화면에서 숨기기

간단하다. 그런데 사실 이 코드에는 약점이 있다.
왜냐하면 div.style.displayinline style 만 읽어오기 때문이다.

그러니까 <div style="display:none;"></div> 처럼 되어 있으면 읽어오겠지만,

<div class='hide'></div> 처럼 class 속성을 사용해서 외부의 css 파일 통해서
display: none 을 해버리면 읽지 못한다는 뜻이다.


이런 상황에서 쓸 수 있는 web-api 가 있다.
바로 window.getComputedStyle(~) 이다.
이걸 쓰면 inline style 뿐만 아니라 외부에 작성된 모든 style 까지 고려한
HtmlElement CSS 객체를 반환해준다. 위의 코드를 이제 수정해보자.


수정된 코드

Array.from(document.querySelectorAll('.popupDiv'))
  .filter(div => window.getComputedStyle(div).display !== 'none')
  .forEach(div => div.style.display = 'none');

별거 아니지만 일단 기록해 둔다.

profile
백엔드를 계속 배우고 있는 개발자입니다 😊

0개의 댓글