TOC
Need to learn JavaScript? jQuery is a JavaScript framework, so if you don't already know about the JavaScript programming language, we recommend that you learn it now: Learn JavaScript

This article is currently in the process of being translated into Vietnamese (~49% done).

DOM manipulation:

Getting and setting CSS classes

Cũng dễ như việc thao tác với nội dung và thuộc thính của element, chúng ta thấy trong chương trước, rất dễ dàng thao tác với CSS của các element. jQuery cho phép thay đổi thông qua phương thức css().

Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).

Tôi tạo ra một vài CSS selector đơn giản như sau:

.bold {
	font-weight: bold;
}

.blue {
	color: blue;
}

Trong ví dụ sau đây, chúng ta sẽ dùng ba phương thức thú vị nhất: hasClass() kiểm tra liệu một hay vài element có class đã được định nghiaw, addClass() để thêm một class vào một hay nhiều element, removeClass() ... bạn sẽ đoán được.

<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a>

<script type="text/javascript">
function ToggleClass(sender)
{
	
	if($(sender).hasClass("bold"))
		$(sender).removeClass("bold");
	else
		$(sender).addClass("bold");
}
</script>

Ví dụ này rất đơn giản. Khi chúng ta bấm vào link, chúng ta gửi vào ToggleClass() chính link đó. Trong đó, ta kiểm tra liệu nó đã có class "bold" hay chưa - nếu có thì chúng ta xóa đi và nếu không thì chúng ta thêm vào. Với jQuery thì không cần phải viết ba dòng code. Chỉ cần viết như sau:

<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">Toggle class</a>

Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:

<div id="divTestArea1">
	<span>Test 1</span><br />
	<div>Test 2</div>
	<b>Test 3</b><br />
</div>
<script type="text/javascript">
$(function()
{
	$("#divTestArea1 span, #divTestArea1 b").addClass("blue");
	$("#divTestArea1 div").addClass("bold blue");
});
</script>

First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!