HTMLDOM要素classList
❮要素オブジェクト例
「myStyle」クラスを要素に追加します。
element.classList.add("myStyle");
要素から「myStyle」クラスを削除します。
element.classList.remove("myStyle");
要素の2つのクラスを切り替えます。
element.classList.toggle("newStyle");
以下のその他の例。
定義と使用法
プロパティは、要素のclassList
CSSクラス名を返します。
このclassList
プロパティは、DOMTokenListオブジェクトを返します。
このclassList
プロパティは読み取り専用ですが、add()メソッドとremove()メソッドを使用してCSSクラスを追加または削除できます。
構文
element.classList
プロパティ値
Value | Description |
length | The number of classes in the list. This property is read-only. |
メソッド
Method | Description |
add(class1, class2, ...) |
Adds one or more classes. |
contains(class) |
Returns true if an element has the class, otherwise false .
|
item(index) | Returns the class name with a specified index. Index starts at 0. Returns null if the index is out of range. |
remove(class1, class2, ...) | Removes one or more classes from an element. Removing a class that does not exist, does NOT throw an error. |
toggle(class, true|false) | Toggles between a class for an element. It removes the class and returns false .If the class does not exist, it adds the class and returns true .The optional second parameter is a boolean that forces the class to be added or removed, regardless of whether or not it already exists. The second parameter is not supported in Internet Explorer 11 or earlier. |
戻り値
Type | Description |
Object | A DOMTokenList. A list of the class names of an element. |
その他の例
要素に複数のクラスを追加します。
element.classList.add("myStyle", "anotherClass", "thirdClass");
要素から複数のクラスを削除します。
element.classList.remove("myStyle", "anotherClass", "thirdClass");
要素に含まれるクラス名の数:
let numb = element.classList.length;
「myDIV」要素のクラス名を取得します。
<div id="myDIV" class="myStyle anotherClass thirdClass">
<p>I am myDIV.</p>
</div>
const list = document.getElementById("myDIV").classList;
要素の最初のクラスを取得します。
let className = element.classList.item(0);
要素には「myStyle」クラスがありますか?
let x = element.classList.contains("myStyle");
要素に「myStyle」クラスがある場合は、「anotherClass」を削除します。
if (element.classList.contains("mystyle")) {
element.classList.remove("anotherClass");
}
クラスを切り替えて、ドロップダウンボタンを作成します。
document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
粘着性のあるナビゲーションバーを作成します。
// Get the navbar
var navbar = document.getElementById("navbar");
//
Get the offset position of the navbar
var sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
if (window.pageYOffset
>= sticky) {
navbar.classList.add("sticky")
}
else {
navbar.classList.remove("sticky");
}
}
ブラウザのサポート
element.classList
すべてのブラウザでサポートされています:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 10-11 | Yes | Yes | Yes | Yes |
❮要素オブジェクト