【初心者でも安心】jQueryでクラスリストの操作をステップバイステップで解説
jQueryで要素のクラスリストを取得する方法
jQueryを使用して、要素のクラスリストを取得するには、いくつかの方法があります。
方法
- attr() メソッド
const element = $('.my-element');
const classList = element.attr('class');
console.log(classList); // 'my-class another-class'
const element = $('.my-element');
const classList = element.prop('class');
console.log(classList); // 'my-class another-class'
- classList プロパティ
const element = $('.my-element')[0];
const classList = element.classList;
console.log(classList); // DOMTokenList(2) ['my-class', 'another-class']
const element = $('.my-element');
element.each(function() {
const classList = $(this).attr('class');
console.log(classList); // 'my-class another-class'
});
補足
attr()
メソッドとprop()
メソッドは、どちらも要素のクラス属性値を取得します。classList
プロパティは、要素のクラスリストを表す DOMTokenList オブジェクトを取得します。each()
メソッドは、複数の要素に対して処理を実行する際に使用できます。
- 上記以外にも、JavaScript の
classList
プロパティやgetElementsByClassName()
メソッドを使用して、要素のクラスリストを取得することもできます。 - 取得したクラスリストは、さまざまな方法で使用できます。例えば、クラス名の存在を確認したり、クラス名を追加・削除したりすることができます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Get class list for element with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="my-element">
This is an element with multiple classes.
</div>
<script>
// 1. attr() メソッド
const element1 = $('.my-element');
const classList1 = element1.attr('class');
console.log(classList1); // 'my-element another-class'
// 2. prop() メソッド
const element2 = $('.my-element');
const classList2 = element2.prop('class');
console.log(classList2); // 'my-element another-class'
// 3. classList プロパティ
const element3 = $('.my-element')[0];
const classList3 = element3.classList;
console.log(classList3); // DOMTokenList(2) ['my-element', 'another-class']
// 4. each() メソッド
const element4 = $('.my-element');
element4.each(function() {
const classList4 = $(this).attr('class');
console.log(classList4); // 'my-element another-class'
});
</script>
</body>
</html>
上記のコードを実行すると、以下の出力がコンソールに表示されます。
my-element another-class
my-element another-class
DOMTokenList(2) ['my-element', 'another-class']
my-element another-class
JavaScript の classList プロパティ
const element = document.querySelector('.my-element');
const classList = element.classList;
// クラス名の存在を確認
if (classList.contains('my-class')) {
// ...
}
// クラス名の追加
classList.add('another-class');
// クラス名の削除
classList.remove('my-class');
JavaScript の getElementsByClassName() メソッド
const elements = document.getElementsByClassName('my-element');
for (const element of elements) {
const classList = element.classList;
// ...
}
javascript jquery html