JavaScript/DOM

[JavaScript]style 프로퍼티 설정 및 가져오기

DevStory 2022. 12. 8.

style 프로퍼티 설정 및 가져오기

이번 포스팅은 JavaScript에서 HTML 요소에 적용된 style 애트리뷰트를 설정 및 가져오는 방법을 소개합니다.


특정 css 프로퍼티 가져오기

<input> 태그는 세 가지 css 프로퍼티인 font-size, color, background-color를 가지고 있습니다.

<input
  id="input-text"
  value="hello"
  style="font-size: 1.5em; color: #ff0000; background-color: #e2e2e2;"
/>

style 애트리뷰트의 css 프로퍼티의 이름은 하이픈(-)이 포함되어 있습니다.

 

따라서, JavaScript에서 css 프로퍼티를 가져오려면 대괄호 표기법을 사용하거나 JavaScript에서 지원하는 프로퍼티를 사용합니다.

const inputNode = document.getElementById("input-text");

// JavaScript에서 지원하는 프로퍼티
console.log(inputNode.style.fontSize);        // 1.5em
console.log(inputNode.style.color);           // rgb(255, 0, 0)
console.log(inputNode.style.backgroundColor); // rgb(226, 226, 226);

// 대괄호 표기법을 사용
console.log(inputNode.style['font-size']);        // 1.5em
console.log(inputNode.style['color']);            // rgb(255, 0, 0)
console.log(inputNode.style['background-color']); // rgb(226, 226, 226)

모든 css 프로퍼티 가져오기

HTML 요소에 적용된 style 애트리뷰트의 모든 css 프로퍼티를 가져오려면 style 프로퍼티를 호출합니다.

 

style 프로퍼티는 CSSStyleDeclaration 객체를 반환하며, 값이 설정된 css 프로퍼티는 인덱스로 접근할 수 있습니다.

<input
  id="input-text"
  value="hello"
  style="font-size: 1.5em; color: #ff0000; background-color: #e2e2e2;"
/>
const inputNode = document.getElementById("input-text");

console.log(inputNode.style);

[실행 결과]

반응형

css 프로퍼티 설정하기 

css 프로퍼티를 설정하는 방법은 다양합니다.

<input
  id="input-text"
  value="hello"
  style="font-size: 1.5em; color: #ff0000; background-color: #e2e2e2;"
/>

기존 style을 재정의하려면 cssText 프로퍼티의 값을 변경합니다.

const inputNode = document.getElementById("input-text");
inputNode.style.cssText = 'color:blue;font-size:15px';

또 다른 방법으로 setAttribute() 메서드를 사용하여 기존 style을 재정의할 수 있습니다.

const inputNode = document.getElementById("input-text");
inputNode.setAttribute('style', 'color:blue;font-size:15px');

 

기존 style을 덮어쓰지 않고 특정 css 프로퍼티만 변경하려면 JavaScript에서 제공하는 프로퍼티를 사용합니다. 아래 예제는 background-color 프로퍼티의 값은 유지하고 color, font-size 프로퍼티의 값만 변경합니다.

const inputNode = document.getElementById("input-text");
inputNode.style.color = 'blue';
inputNode.style.fontSize = '12px';

또 다른 방법으로 cssText 프로퍼티와 += 연산자를 사용하여 기존 style을 덮어쓰지 않고 특정 css 프로퍼티만 변경할 수 있습니다.

const inputNode = document.getElementById("input-text");
inputNode.style.cssText += 'color:blue;font-size:15px';

정리

  • JavaScript에서 style 프로퍼티를 사용하여 HTML 요소에 적용된 css 프로퍼티를 가져오거나 설정할 수 있습니다.
  • style 프로퍼티는 모든 css 프로퍼티의 정보가 담긴 CSSStyleDeclaration 객체를 반환합니다.
반응형

댓글