removeClass() 方法能從匹配元素中移除一個或多個指定的 CSS 類名,是實現狀態重置、樣式切換、表單驗證提示清除等場景的核心工具。
// 移除單個 class
$(selector).removeClass("class-name");
// 移除多個 class(空格分隔)
$(selector).removeClass("class1 class2 class3");
// 移除所有 class
$(selector).removeClass();
// 使用函數條件移除
$(selector).removeClass(function(index, currentClass) {
return index % 2 === 0 ? "even" : "odd";
});
點擊按鈕移除所有標題與段落的 red class:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").removeClass("red");
});
});
</script>
<style type="text/css">
.red { color: red; font-weight: bold; }
.important { font-weight: bold; font-size: xx-large; }
.blue { color: blue; }
</style>
</head>
<body>
<h1 class="red">Heading 1</h1>
<h2 class="red">Heading 2</h2>
<p class="red">This is a paragraph.</p>
<p>This is another paragraph.</p>
<br>
<button>Remove class from elements</button>
</body>
</html>
removeClass("error success") 清除舊提示removeClass("active") 重置所有標籤.animate(...).promise().done(() => $el.removeClass("animating"))$("body").removeClass("theme-dark theme-blue").addClass("theme-light")// 代替手動判斷
if ($el.hasClass("open")) $el.removeClass("open");
else $el.addClass("open");
// 直接使用
$el.toggleClass("open");
removeClass() 與 addClass()、toggleClass() 組成了 jQuery 類名操作的「鐵三角」,熟練掌握它們的組合用法能讓 DOM 樣式控制得心應手。