HTML DOM 요소 클래스 목록
❮ 요소 개체예시
요소에 "myStyle" 클래스를 추가합니다.
element.classList.add("myStyle");
요소에서 "myStyle" 클래스를 제거합니다.
element.classList.remove("myStyle");
요소에 대한 두 클래스 간 전환:
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 |
❮ 요소 개체