」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 玩轉classList API - SitePoint指南

玩轉classList API - SitePoint指南

發佈於2025-04-18
瀏覽:256

玩轉classList API - SitePoint指南

Key Takeaways

  • The classList API, introduced in HTML5, provides methods and properties to manage class names of DOM elements, making it easier to add, remove, or toggle class names in JavaScript.
  • The classList API exposes methods such as add(), remove(), toggle(), contains(), item(), length, and toString() to perform operations on class names.
  • The classList API is widely supported among desktop and mobile browsers except for Internet Explorer, which started supporting this API from version 10.
  • The classList API simplifies the process of manipulating classes, making code cleaner and more efficient, and eliminating the need for complex string manipulation or using regular expressions to manage classes.
Since the creation of HTML and the birth of the first websites, developers and designers have tried to customize the look and feel of their pages. This need became so important that a standard, called CSS, was created to properly manage style and separate it from the content. In today’s highly interactive websites, you often need to add, remove, or toggle class names (usually referred to as “CSS classes”). Historically, dealing with these changes in JavaScript was slightly complicated because there were no built-in methods to perform these actions. This was the case until HTML5 introduced the classList API. In this article, we’ll discover how this API works and the methods it provides. Note: The term “CSS classes” is often used to refer to class names. These are the strings you put inside the class attribute of an element. However, there is an interesting article suggesting that the term is incorrect and you should avoid it. For the sake of brevity, in this article I’m going to use the term “classes” as a shortcut for “class names”.

What is the classList API?

The classList API provides methods and properties to manage class names of DOM elements. Using it, we can perform operations such as adding and removing classes, or checking if a given class is present on an element. The classList API exposes these methods and properties via an attribute of the DOM element, called classList. This attribute is of type DOMTokenList, and contains the following methods and properties:
  • add(class1, class2, ...): Adds one or more classes to the element’s class list.
  • contains(class): Returns true if the list of classes contains the given parameter, and false otherwise.
  • item(index): Returns the class at position index, or null if the number is greater than or equal to the length of the list. The index is zero-based, meaning that the first class name has index 0.
  • length: This is a read-only property that returns the number of classes in the list.
  • remove(class1, class2, ...): Removes one or more classes from the element’s class list.
  • toString(): Returns the element’s list of classes as a string.
  • toggle(class[, force]): Removes the given class from the class list, and returns false. If the class didn’t exist, it is added, and the function returns true. If the second argument is provided, it’ll force the class to be added or removed based on its truthiness. For example, setting this value to true causes the class to be added, regardless of whether or not it already existed. By setting this value to false, the class will be removed.
If you’re familiar with jQuery, you may think that the add() and remove() methods perform the same operation on multiple classes by passing a list of space-separated class names (for example add("red bold bigger")). This is not the case. To add or remove more classes at once, you’ve to pass a string for each classes (for example add("red", "bold", "bigger")). As I pointed out, the toggle() method has an optional argument that we can use to force a given action. In other words, if the second parameter of toggle() is false, it acts as the remove() method; if the second parameter is true, it acts as the add() method. Now that we’ve described the methods and the properties of this API, let’s see some examples of it in action. Each of the code samples shown below will perform an action assuming the presence of the following HTML element on the page.
 id="element" class="description">>

Adding a Class

To add the class name “red” to the class attribute of the element, we can write the following:
document.getElementById('element').classList.add('red');
// 
To add multiple classes, for example “red” and “bold”, we can write this:
document.getElementById('element').classList.add('red', 'bold');
// 
Note that if one of the provided classes was already present, it won’t be added again.

Removing a Class

To delete a class, for example “description”, we would write the following:
document.getElementById('element').classList.remove('description');
// 
To remove multiple classes at once, we write:
document.getElementById('element').classList.remove('description', 'red');
// 
Note that an error is not thrown if one of the named classes provided wasn’t present.

Toggling a Class

Sometimes we need to add or remove a class name based on a user interaction or the state of the site. This is accomplished using the toggle() method, as demonstrated below.
document.getElementById('element').classList.toggle('description');
// 

document.getElementById('element').classList.toggle('description');
// 

Retrieving a Class

The classList API provides a method of retrieving class names based on it’s position in the list of classes. Let’s say that we want to retrieve the first and the third classes of our element. We would write the following:
document.getElementById('element').classList.item(0);
// returns "description"

document.getElementById('element').classList.item(2);
// returns null

Retrieving the Number of Classes

Although not very common, there are cases where we may need to know the number of classes applied to a given element. The classList API allows us to retrieve this number through the length property as shown below:
console.log(document.getElementById('element').classList.length);
// prints 1

Determine if a Class Exists

Sometimes we may want to execute a given action based on the presence of a certain class. To perform the test we use the contains() method in the following fashion:
if (document.getElementById('element').classList.contains('description')) {
   // do something...
} else {
   // do something different...
}

Returning the Class List as a String

To return the list of classes as a string, we can use the toString() method, which is shown below.
console.log(document.getElementById('element').classList.toString());
// prints "description"

document.getElementById('element').classList.add('red', 'bold');
console.log(document.getElementById('element').classList.toString());
// prints "description red bold"

Browser Compatibility

The classList API is widely supported among desktop and mobile browsers except for Internet Explorer. IE began supporting this API starting in version 10. More specifically, you can use this API in Chrome 8 , Firefox 3.6 , Internet Explorer 10 , Safari 5.1 , and Opera 11.5 . As we’ve seen the classList API is very straightforward and, as you may guess, polyfilling it is not difficult. Creating your own polyfill should be straightfoward, but if you want something that already exists, you can use classList.js by Eli Grey.

Demo

This section provides a simple demo that allows you to experiment with the concepts explained in this article. The demo page contains two basic fields: a select element containing the methods and properties exposed by the API, and a textbox where we can write parameters to pass. As you’ll see, the demo doesn’t explicitly call the methods, but instead uses a simple trick (the use of the JavaScript apply() method), resulting in fewer lines of code. Because some browsers don’t support the API, we perform a check, and if it fails we display the message “API not supported”. If the browser does support the classList API, we attach a listener for the click event of the button so that once clicked, we execute the chosen method. A live demo of the code is available here.

>
  >
     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0"/>
    >ClassList API Demo>
    
      body
      {
        max-width: 500px;
        margin: 2em auto;
        font-size: 20px;
      }

      h1
      {
        text-align: center;
      }

      .hidden
      {
        display: none;
      }

      .field-wrapper
      {
        margin-top: 1em;
      }

      #log
      {
        height: 200px;
        width: 100%;
        overflow-y: scroll;
        border: 1px solid #333333;
        line-height: 1.3em;
      }

      .button-demo
      {
        padding: 0.5em;
        margin: 1em;
      }

      .author
      {
        display: block;
        margin-top: 1em;
      }
    >
  >
  >
    

>

ClassList API>

>

Live sample element>
id="showcase"> <span ">></span">>
>

>

Play area>
>
class="field-wrapper"> Methods and Properties:> add()> contains()> item()> length> remove()> toString()> toggle()> >
>
class="field-wrapper"> Parameters (use spaces for multiple parameters):> type="text" id="parameter">>
>
Execute>
>
id="d-unsupported" class="hidden">API not supported>

>

Log>
id="log">
>
Clear log> id="play-element" class="description">> if (!'classList' in document.createElement('span')) { document.getElementById('c-unsupported').classList.remove('hidden'); document.getElementById('execute').setAttribute('disabled', 'disabled'); } else { var playElement = document.getElementById('play-element'); var method = document.getElementById('method'); var parameter = document.getElementById('parameter'); var log = document.getElementById('log'); var showcase = document.getElementById('showcase'); document.getElementById('clear-log').addEventListener('click', function() { log.innerHTML = ''; }); document.getElementById('execute').addEventListener('click', function() { var message = method.value; if (method.value === 'length') { message = ': ' playElement.classList[method.value] } else { var result = playElement.classList[method.value].apply(playElement.classList, parameter.value.split(' ')); showcase.textContent = playElement.outerHTML; if (method.value === 'add' || method.value === 'remove' || method.value === 'toggle') { message = ' class "' parameter.value '"'; } else { message = ': ' result; } } log.innerHTML = message '
' log.innerHTML;
}); } > > >

Conclusions

In this article, we’ve learned about the classList API, its methods, and its properties. As we’ve seen, this API helps us in managing the classes assigned to a given element – and it is very easy to use and. This API is widely supported among desktop and mobile browsers, so we can use it safely (with the help of a polyfill if needed). As a last note, don’t forget to play with the demo to gain a better grasp of this API and its capabilities.

Frequently Asked Questions about ClassList API

What is the ClassList API and why is it important in JavaScript?

The ClassList API is a powerful tool in JavaScript that allows developers to manipulate the class attribute of HTML elements. It provides methods to add, remove, toggle, and check the presence of classes in an element’s class attribute. This is important because it simplifies the process of manipulating classes, making your code cleaner and more efficient. It also eliminates the need for complex string manipulation or using regular expressions to manage classes.

How does the ClassList API differ from the traditional methods of manipulating classes in JavaScript?

Traditional methods of manipulating classes in JavaScript involve directly accessing the className property of an element and performing string operations. This can be cumbersome and error-prone. The ClassList API, on the other hand, provides a more intuitive and straightforward way to manipulate classes. It offers specific methods for adding, removing, and toggling classes, making it easier and safer to use.

Can I use the ClassList API on all browsers?

The ClassList API is widely supported across all modern browsers. However, it’s worth noting that Internet Explorer 9 and older versions do not support the ClassList API. You can check the compatibility of the ClassList API on different browsers on websites like “Can I use”.

How do I add a class to an element using the ClassList API?

To add a class to an element using the ClassList API, you can use the add() method. Here’s an example:

element.classList.add("myClass");

In this example, “myClass” is the class you want to add to the element.

How do I remove a class from an element using the ClassList API?

To remove a class from an element using the ClassList API, you can use the remove() method. Here’s an example:

element.classList.remove("myClass");

In this example, “myClass” is the class you want to remove from the element.

How do I check if an element has a specific class using the ClassList API?

To check if an element has a specific class using the ClassList API, you can use the contains() method. Here’s an example:

if (element.classList.contains("myClass")) {
// do something
}

In this example, “myClass” is the class you want to check.

How do I toggle a class in an element using the ClassList API?

To toggle a class in an element using the ClassList API, you can use the toggle() method. Here’s an example:

element.classList.toggle("myClass");

In this example, “myClass” is the class you want to toggle. If the element already has the class, it will be removed. If it doesn’t have the class, it will be added.

Can I add or remove multiple classes at once using the ClassList API?

Yes, you can add or remove multiple classes at once using the ClassList API. You just need to pass the classes as separate arguments to the add() or remove() method. Here’s an example:

element.classList.add("class1", "class2", "class3");
element.classList.remove("class1", "class2", "class3");

In this example, “class1”, “class2”, and “class3” are the classes you want to add or remove.

Can I use the ClassList API with SVG elements?

Yes, you can use the ClassList API with SVG elements. However, it’s worth noting that this feature is not supported in Internet Explorer.

What are some common use cases for the ClassList API?

The ClassList API is commonly used for adding, removing, or toggling classes to show or hide elements, change their appearance, or trigger animations. It’s also used to check the presence of a class to perform some action. For example, you might want to check if an element has a “hidden” class before showing it, or you might want to add a “highlight” class to an element when it’s clicked.

最新教學 更多>
  • 如何使用“ JSON”軟件包解析JSON陣列?
    如何使用“ JSON”軟件包解析JSON陣列?
    parsing JSON與JSON軟件包 QUALDALS:考慮以下go代碼:字符串 } func main(){ datajson:=`[“ 1”,“ 2”,“ 3”]`` arr:= jsontype {} 摘要:= = json.unmarshal([] byte(...
    程式設計 發佈於2025-05-07
  • Java為何無法創建泛型數組?
    Java為何無法創建泛型數組?
    通用陣列創建錯誤 arrayList [2]; JAVA報告了“通用數組創建”錯誤。為什麼不允許這樣做? 答案:Create an Auxiliary Class:public static ArrayList<myObject>[] a = new ArrayList<my...
    程式設計 發佈於2025-05-07
  • 如何同步迭代並從PHP中的兩個等級陣列打印值?
    如何同步迭代並從PHP中的兩個等級陣列打印值?
    同步的迭代和打印值來自相同大小的兩個數組使用兩個數組相等大小的selectbox時,一個包含country代碼的數組,另一個包含鄉村代碼,另一個包含其相應名稱的數組,可能會因不當提供了exply for for for the uncore for the forsion for for ytry...
    程式設計 發佈於2025-05-07
  • Java中假喚醒真的會發生嗎?
    Java中假喚醒真的會發生嗎?
    在Java中的浪費喚醒:真實性或神話? 在Java同步中偽裝喚醒的概念已經是討論的主題。儘管存在這種行為的潛力,但問題仍然存在:它們實際上是在實踐中發生的嗎? Linux的喚醒機制根據Wikipedia關於偽造喚醒的文章,linux實現了pthread_cond_wait()功能的Linux實現,...
    程式設計 發佈於2025-05-07
  • 找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
    找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
    如何在mySQL中使用mySql 檢索最大計數,您可能會遇到一個問題,您可能會在嘗試使用以下命令:理解錯誤正確找到由名稱列分組的值的最大計數,請使用以下修改後的查詢: 計數(*)為c 來自EMP1 按名稱組 c desc訂購 限制1 查詢說明 select語句提取名稱列和每個名稱...
    程式設計 發佈於2025-05-07
  • 在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在JTable中維護jtable單元格渲染後,在JTable中,在JTable中實現自定義單元格渲染和編輯功能可以增強用戶體驗。但是,至關重要的是要確保即使在編輯操作後也保留所需的格式。 在設置用於格式化“價格”列的“價格”列,用戶遇到的數字格式丟失的“價格”列的“價格”之後,問題在設置自定義單元...
    程式設計 發佈於2025-05-07
  • 如何解決AppEngine中“無法猜測文件類型,使用application/octet-stream...”錯誤?
    如何解決AppEngine中“無法猜測文件類型,使用application/octet-stream...”錯誤?
    appEngine靜態文件mime type override ,靜態文件處理程序有時可以覆蓋正確的mime類型,在錯誤消息中導致錯誤消息:“無法猜測mimeType for for file for file for [File]。 application/application/octet...
    程式設計 發佈於2025-05-07
  • 如何有效地選擇熊貓數據框中的列?
    如何有效地選擇熊貓數據框中的列?
    在處理數據操作任務時,在Pandas DataFrames 中選擇列時,選擇特定列的必要條件是必要的。在Pandas中,選擇列的各種選項。 選項1:使用列名 如果已知列索引,請使用ILOC函數選擇它們。請注意,python索引基於零。 df1 = df.iloc [:,0:2]#使用索引0和1 ...
    程式設計 發佈於2025-05-07
  • 如何使用組在MySQL中旋轉數據?
    如何使用組在MySQL中旋轉數據?
    在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。讓我們考慮以下查詢: select data d.data_ti...
    程式設計 發佈於2025-05-07
  • Python讀取CSV文件UnicodeDecodeError終極解決方法
    Python讀取CSV文件UnicodeDecodeError終極解決方法
    在試圖使用已內置的CSV模塊讀取Python中時,CSV文件中的Unicode Decode Decode Decode Decode decode Error讀取,您可能會遇到錯誤的錯誤:無法解碼字節 in position 2-3: truncated \UXXXXXXXX escapeThi...
    程式設計 發佈於2025-05-07
  • 左連接為何在右表WHERE子句過濾時像內連接?
    左連接為何在右表WHERE子句過濾時像內連接?
    左JOIN CONUNDRUM:WITCHING小時在數據庫Wizard的領域中變成內在的加入很有趣,當將c.foobar條件放置在上面的Where子句中時,據說左聯接似乎會轉換為內部連接。僅當滿足A.Foo和C.Foobar標準時,才會返回結果。 為什麼要變形?關鍵在於其中的子句。當左聯接的右側...
    程式設計 發佈於2025-05-07
  • PHP SimpleXML解析帶命名空間冒號的XML方法
    PHP SimpleXML解析帶命名空間冒號的XML方法
    在php 很少,請使用該限制很大,很少有很高。例如:這種技術可確保可以通過遍歷XML樹和使用兒童()方法()方法的XML樹和切換名稱空間來訪問名稱空間內的元素。
    程式設計 發佈於2025-05-07
  • 為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    程式設計 發佈於2025-05-07
  • 反射動態實現Go接口用於RPC方法探索
    反射動態實現Go接口用於RPC方法探索
    在GO 使用反射來實現定義RPC式方法的界面。例如,考慮一個接口,例如:鍵入myService接口{ 登錄(用戶名,密碼字符串)(sessionId int,錯誤錯誤) helloworld(sessionid int)(hi String,錯誤錯誤) } 替代方案而不是依靠反射...
    程式設計 發佈於2025-05-07
  • MySQL中如何高效地根據兩個條件INSERT或UPDATE行?
    MySQL中如何高效地根據兩個條件INSERT或UPDATE行?
    在兩個條件下插入或更新或更新 solution:的答案在於mysql的插入中...在重複鍵更新語法上。如果不存在匹配行或更新現有行,則此功能強大的功能可以通過插入新行來進行有效的數據操作。如果違反了唯一的密鑰約束。 實現所需的行為,該表必須具有唯一的鍵定義(在這種情況下為'名稱'...
    程式設計 發佈於2025-05-07

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3