My Boundary As Much As I Experienced

css) 자바스크립트에서 CSS 변수를 읽어오는 방법은 무엇인가? 본문

FrontEnd/HTML&CSS

css) 자바스크립트에서 CSS 변수를 읽어오는 방법은 무엇인가?

Bumang 2024. 3. 4. 19:28

Element.style 속성과 GetComputedStyle() 메소드의 차이점

쿼리셀렉터 혹은 getElement... 메소드로 가져온 HTMLElement의 css 속성을 조작하는데엔 2가지 방법이 있다.

Element.style와 getComputedStyle이다. (사실 추가로 css in JS인 스타일드 컴포넌트를 쓰면 state로 조작할 수 있긴 하다..)

이 두 개의 차이점을 알아보자.

 

아래는 각기 다른 형태로 작성된 엘리먼트들이다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #second-element {
        color: green;
      }
    </style>
  </head>
  <body>
    <div id="first-element" style="color: red;">
      첫 번째 엘리먼트
    </div>
    <div id="second-element">
      두 번째 엘리먼트
    </div>
  </body>
</html>

첫 번째 엘리먼트는 인라인 방식으로 해당 엘리먼트에 글자색 스타일을 직접 선언하고, 두 번째 엘리먼트는 body태그 바깥에서 style 태그를 이용해서 외부에서 선언하도록 했다.

 

Element.style 을 활용

element.style을 활용한 경우, 인라인 방식으로 쓰여진 값은 불러오고 인라인 방식으로 쓰여지지 않은(클래스로 부착된) css 프로퍼티는 불러오지 못한다.

// 첫 번째 엘리먼트
const style = document.getElementById('first-element').style;

console.log(style.color) // "red"

// 두 번째 엘리먼트
const element = document.getElementbyId('second-element');

console.log(element.style.color) // ""

 

클래스 혹은 아이디에 선언된 스타일들이 안 먹히는 건 element.style은 html파일의 attribute를 탐색하기 때문이다.

 

 

GetComputedStyle 을 사용한 경우

브라우저가 제공하는 window.getComputedStyle() 메소드는 인자로 전달받은 엘리먼트에 최종적으로 적용된 모든 CSS 속성 값을 담은 객체를 반환한다. (브라우저가 제공한다는건 node 환경에서는 사용 불가하단 뜻이다)

객체 중에 원하는 값(color, background-color, ...) 등 모두 접근 가능하다.

const element = document.getElementById('second-element');

console.log(window.getComputedStyle(element).color) // "rgb(0,128,0)"

 

getComputedStyle은 최종적으로 렌더된 속성을 가져오기 때문에 두 번째 엘리먼트도 잘 가져오는걸 볼 수 있다.

클래스에 적용했던 css도 최종적으로 브라우저에 렌더됐다면 다 가져오기 때문이다.

 

Element.style 속성과 getComputedStyle() 메소드의 핵심 차이

그렇다면 getComputedStyle()만 쓰면 되지 style객체는 왜 쓰나?

Element.style 속성과 getComputedStyle()의 핵심 차이는 사용 목적에 있다.


getComputedStyle()메소드에서 반환된 객체는 읽기 전용이며, 해당 엘리먼트의 스타일을 검사하는 데 사용할 수 있다.
따라서 getComputedStyle()메소드를 이용하여 새로운 스타일 변경을 시도하면, 아래와 같이 에러가 발생하게 된다.

 

 

 

이와 달리, Element.style 속성은 해당 엘리먼트에게 새로운 스타일을 설정하는 데 사용하게 된다.
Element.style 속성을 통해, 해당 DOM 노드에 접근하여 직접적으로 스타일을 주입시키는 것이다.