yongyong-e
[jQuery] 문서 객체 다루기 - 2 본문
0) 개요
jQuery에서 클래스 속성에 대해 추가 및 제거하는 방법
1) 문서 객체의 클래스 속성 추가
1. attr 함수를 통해 class 속성을 지정하여 스타일을 적용하는 방법
<!DOCTYPE html>
<html>
<head>
<title>jQuery 문서 객체 다루기 - 2</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<style>
.header { text-align: center; }
.red-text { color: red; }
</style>
</head>
<body>
<h1>Hello World</h1>
<script>
$("h1").attr("class", "header red-text")
</script>
</body>
</html>
2. addClass 함수를 통해 스타일을 적용하는 방법
<!DOCTYPE html>
<html>
<head>
<title>jQuery 문서 객체 다루기 - 2</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<style>
.header { text-align: center; }
.red-text { color: red; }
</style>
</head>
<body>
<h1>Hello World</h1>
<script>
$("h1").addClass("header")
$("h1").addClass("red-text")
</script>
</body>
</html>
2) 문서 객체의 클래스 속성 제거
다음 코드는 "Hello World"라는 문장을 center 및 red 스타일 클래스를 적용하고 2초 후에 지정한 클래스를 제거하는 코드입니다.
<!DOCTYPE html>
<html>
<head>
<title>jQuery 문서 객체 다루기 - 2</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<style>
.header { text-align: center; }
.red-text { color: red; }
</style>
</head>
<body>
<h1>Hello World</h1>
<script>
$("h1").addClass("header")
$("h1").addClass("red-text")
setTimeout(function () {
$("h1").removeClass("header")
$("h1").removeClass("red-text")
}, 1000 * 2)
</script>
</body>
</html>
결과
2초 후
'웹 프로그래밍 > jQuery' 카테고리의 다른 글
[jQuery] 이벤트 연결하기 (0) | 2019.09.05 |
---|---|
[jQuery] 문서 객체 다루기 - 3 (0) | 2019.09.04 |
[jQuery] 문서 객체 다루기 - 1 (0) | 2019.09.04 |
[jQuery] 문서 객체 생성 방법 (0) | 2019.09.04 |
[jQuery] 라이브러리 사용 설정 (0) | 2019.09.04 |
Comments