본문 바로가기

Web Application/jQuery

07.10 - jQuery Reference - .addClass()

.addClass(className)
설명 : 각각의 일치하는 요소에 대해 지정된 클레스를 추가합니다.

Original Reference : http://api.jquery.com/addClass/

.addClass (className) - 추가된 버젼 1.0

className 일치하는 요소에 추가할 하나 이상의 클레스 이름.

.addClass ( function(index, class) ) - 추가된 버젼 1.4

funtion(index, class) A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments.

중요. 이 메서드는 클래스를 대신하지 않습니다. 이것은 간단하게 준비된 모든 요소에 대하여 클레스를 추가하여 줍니다.

일치하는 요소에 대하여 공백을 구분으로 하여 한 번에 한나 이상의 클래스를 다음과 같이 추가할 수 있습니다.
$('p').addClass('myClass yourClass');
이 메서드는 보통 다음과 같이 .removeClass() 같은 요소와 함께 사용되기도 합니다.
$('p').removeClass('myClass noClass').addClass('yourClass');
여기서, myClass 와 noClass 는 모든 단락에서 yourClass 가 추가되는 동안 제거됩니다.

jQuery 1.4 부터는 .addClass() 메서드는 클래스 이름을 함수에 전달하여 사용할 수 있습니다.
$('ul li:last').addClass(function() {
  return 'item-' + $(this).index();
});
이 예제는 5개의 unordered list 형식의 <li> 요소의 마지막 <li> 에 대하여 "item-4" 라는 클레스를 추가합니다.

Examples:
Example: 일치하는 요소에 'selected' 클래스 추가하기.
<!DOCTYPE html>
<html>
<head>
  <style>

  p { margin: 8px; font-size:16px; }
  .selected { color:blue; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
<script>$("p:last").addClass("selected");</script>
</body>
</html>

Example: 일치하는 요소에 'selected' 및 'highlight' 클래스 추가하기.
<!DOCTYPE html>
<html>
<head>
  <style>

  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
<script>$("p:last").addClass("selected highlight");</script>
</body>
</html>


2010.07.10 - 레퍼런스 일부 번역
2010.07.10 / 레퍼런스 번역 & 정리 - by Kinesis(김 해광)
- 불법적인 펌이나 스크랩, 편집, 재유포를 금지합니다.
- 필요하다면 이 페이지로 접근할 수 있는 링크를 남겨주세요.

 

'Web Application > jQuery' 카테고리의 다른 글

07.10 - jQuery Reference - .attr()  (0) 2010.07.10
07.10 - jQuery Reference - Attributes  (0) 2010.07.10