일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- row-gap
- HTML
- sass
- Pseudo
- Flex
- property
- column-gap
- CLASS
- JavaScript
- tailwindcss
- 친해지기
- Coda
- HASH
- 코딩퀴즈
- 선택자
- 코드다이어리
- frontend
- display
- 코딩문제
- DOM
- 웹폰트
- regexp
- 가상클래스
- CSS
- js
- Grid
- 코딩일기
- 정규식표현
- 코딩테스트
- 코드일기
- Today
- Total
< Code diaries />
Javascript 로 CSS 속성 가져오기, 수정하기 본문
오늘은 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 |
---|