< Code diaries />

Javascript 로 CSS 속성 가져오기, 수정하기 본문

Javascript-DOM/03 - CSS 다루기

Javascript 로 CSS 속성 가져오기, 수정하기

ejey 2024. 6. 4. 08:50

오늘은 javascript에서 css 속성을 어떻게 다루는지,

어떤 명령어들이 있는지 한 번 정리해 보려고 해요.

궁금하신 점은 답글에 남겨주세요

 

 

<h1 class="title" style="text-align:center;">Hello World</h1>

<script>
	const h1 = document.querySelector('.title');
</script>

 

1. style 속성을 이용하여 <h1>태그의 css를 변경하기

h1.style.backgroundColor = 'tomato';
h1.style.fontSize = '12px';
h1.style.border = '1px solid olive';

String 형식으로 들어갈 때에 따옴표안에 세미콜론(;)을 적지 않도록 주의하자.

2. cssText 속성을 이용하여 여러 css를 한번에 수정하기.

h1.style.cssText = 'font-size:20px; color:blue';

 

3. cssText 속성을 이용하여 요소에 들어있는 css 속성 가져오기

const styles = h1.style.cssText;
console.log(styles)


// output
// 'font-size:20px; color:blue;'

cssText는 html 태그에 직접적으로 inline style sheet 방식으로 적혀있는 것만 읽어올 수 있다. css 문서나 내부스타일 시트로 정의된 것들은 불러올 수 없다.

 

 

Javascript로 CSS의 변수나 다른것들도 다룰 수 가 있는데요,

그건 다음에 포스팅해볼게요~

 

 

[ 아래의 2가지 속성은 다른 것이니 혼동하지 마시라고 둘다 링크 드려요 - 참고로만 가볍게 보세요 잘 안써요 ]

 

https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/cssText

 

CSSRule: cssText property - Web APIs | MDN

The cssText property of the CSSRule interface returns the actual text of a CSSStyleSheet style-rule.

developer.mozilla.org

 

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/cssText

 

CSSStyleDeclaration: cssText property - Web APIs | MDN

The cssText property of the CSSStyleDeclaration interface returns or sets the text of the element's inline style declaration only.

developer.mozilla.org

 

반응형

'Javascript-DOM > 03 - CSS 다루기' 카테고리의 다른 글

Javascript 로 CSS 변수 값 조절하기  (0) 2024.06.07