티스토리 뷰

const heroElement = document.getElementById('hero');
let heroLeftInline = heroElement.style.left;

console.log("heroElement.style.left", heroLeftInline); // ""

강의를 들으며 웹게임을 진행하던 중에 getElementById로 불러온 요소에 style.left를 확인하려고 하니 외부 css 파일에서 스타일을 설정했음에도 아무 값도 입력되지 않았다.

 

이유

HTMLElement.style은 태그 내에 인라인 형식으로 정의된 것만 가져오므로 getElementById로 불러온 요소는 인라인 형식으로 정의되어있는 스타일 속성만 읽어올 수 있다.

 

Element.style로 속성 값 확인해보기

  • html에 인라인스타일로 style을 넣었을 때 (읽어오기 가능)
<div id="style" style="border: 1px solid #c8c8c8; width: 200px; height: 200px"></div>
const box = document.getElementById("style");
console.log(box.style.border); // 1px solid rgb(200, 200, 200)

 

  • <style>태그에서 style을 설정했을 때 (읽어오기 불가능)
<style>
      #style {
        border: 1px solid #c8c8c8;
        width: 200px;
        height: 200px;
      }
    </style>
<div id="style"></div>
const box = document.getElementById("style");
console.log(box.style.border); // ""

 

  • 외부 css파일에서 style을 설정했을 때 (읽어오기 불가능)
<div id="style"></div>
#style {
  border: 1px solid #c8c8c8;
  width: 200px;
  height: 200px;
}
const box = document.getElementById("style");
console.log(box.style.border); // ""

const heroElement = document.getElementById('hero');
let heroLeftInline = heroElement.style.left;
let heroLeftGetComputedStyle = getComputedStyle(heroElement).left;

console.log("heroElement.style.left",heroLeftInline); // ""
console.log("getComputedStyle",heroLeftGetComputedStyle); // 400

그래서 해결방법으로 브라우저에서 제공하는 getComputedStyle 메소드를 사용하여 left값을 읽어왔다.

 

getComputedStyle()

인자로 전달받은 요소의 모든 CSS 속성값을 담은 객체를 회신한다. 이 속성값들은, 해당 요소에 대하여 활성 스타일시트와 속성값에 대한 기본 연산이 모두 반영된 결과값이다.

window.getComputedStyle(element[, pseudoElt]);

 

 

Window.getComputedStyle() - Web APIs | MDN

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.

developer.mozilla.org

Window.getComputedStyle(element[, pseudoElt])

첫번째 인자 element는 속성값을 얻으려는 요소이고, 두번째 인자 pseudo element는 ::after, ::before, ::marker, ::line-marker 같은 가상 요소가 있을 때 사용하며 보통의 요소들은 생략되거나 null이어야 한다.

 

getComputedStyle()은  CSSStyleDeclaration object 를 반환하기 때문에 getPropertyValue()를 사용하여 값을 받아 올 수도 있다.

 

CSSStyleDeclaration.getPropertyValue()

지정된 CSS 속성값을 포함한 문자열을 반환한다. 설정되지 않은 속성이라면 빈 문자열을 반환한다.

getPropertyValue(property)

Element.style과 getComputedStyle()의 차이점

Element.style속성은 DOM 노드에 접근하여 직접적으로 스타일을 주입시켜 특정한 엘리먼트에게 새로운 스타일을 설정하는 데 사용한다.

 

getComputedStyle()에서 반환된 객체는 읽기 전용이며, <style> 또는 외부 stylesheet로 설정되는 것도 포함해서 요소의 스타일을 검사하는 데 사용할 수 있다. getComputedStyle()을 이용하여 새로운 스타일 변경을 시도하면 에러가 발생한다.

const content = document.getElementById("content");
getComputedStyle(content).color = "rgb(100,100,100)"; // 에러발생
// Uncaught DOMException: Failed to set the 'color' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'color' property is read-only.
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함